Reputation: 31
I am not sure what is going on with this code, I believe it has something to do with how my variables are scoped, but changing them from "my" to "our" doesn't do anything. The error comes in the second if block where I try to get it to print $question1, perl says that "$question1 requires a specific package name". The code there is just a test for what I need to do later in the program. I just need the $question variables to be able to be used throughout my program.
foreach my $line ( split /:/, $test ) {
my $match1 = "1";
my $match2 = "2";
if ( $line =~ /$match1/ ) {
my $question1 = $line;
print "$question1\n";
}
if ( $line =~ /$match2/ ) {
my $question2 = $line;
print "$question2\n";
print "$question1\n";
}
}
Upvotes: 0
Views: 61
Reputation: 183321
To increase the scope of a variable beyond a certain block, you need to move its declaration outside of that block, like so:
my ($question1, $question2); # both are now initialized to undef
foreach my $line (split /:/, $test) {
my $match1 = "1";
my $match2 = "2";
if ($line =~ /$match1/) {
$question1 = $line; # NOT declaring with 'my', JUST assigning
}
if ($line =~ /$match2/) {
$question2 = $line; # NOT declaring with 'my', JUST assigning
}
}
Upvotes: 2