2

For this script users can input what projects they want used as a command line argument ($opt_proj) in a csv format like this: Proj1,Proj2,Proj3

I want to split these up to get each individually, but I'm not sure why the split command won't populate my array with the projects.

Code:

my @projects;
if ( defined $opt_proj ) {
    print $opt_proj;
    my @projects=split /,/,$opt_proj;
}   
print "@projects\n";
exit;

$opt_proj contains the data and prints out Proj1,Proj2,Proj3. But, @projects appears to be empty. I have also tried printing the contents of @projects with a foreach loop and same result.

1 Answer 1

4

The problem is scope. Just remove the my keyword inside the if block:

use warnings;
use strict;

my $opt_proj = 'Proj1,Proj2,Proj3';
my @projects;
if ( defined $opt_proj ) {
    print $opt_proj, "\n";
    @projects=split /,/,$opt_proj;
}   
print "@projects\n";
exit;

This prints:

Proj1,Proj2,Proj3
Proj1 Proj2 Proj3

Your code creates a new variable @projects inside the if block which can not be seen outside the block.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.