0

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";
    }
}
1
  • Have you thought this through? What value of $question1 do you expect to be printed in case $match1 doesn't match and $match2 does? Commented Oct 18, 2014 at 20:06

1 Answer 1

2

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
    }
}
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.