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.
CodePudding user response:
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.