What I want to achieve in subroutine in_sequence is as follows:use strict; my $seq1 = 'aabcdefg'; my $seq2 = 'aabcdefgabcde'; sub in_sequence { my $str = shift; # fetch the string value my $ok = 1; # set private variable $ok = 1 $str =~ m/(.)(.)(??{ $ok = 0 if $2 lt $1; 0 })/; return $ok; } print "Sequence is ", in_sequence($seq1)?"good":"bad", "\n"; print "Sequence is ", in_sequence($seq2)?"good":"bad", "\n";
When I ran the code, I got the following output:use strict; my $seq1 = 'aabcdefg'; my $seq2 = 'aabcdefgabcde'; sub in_sequence_debug { my $str = shift; my $ok = 1; print "Value of OK is $ok\n"; $str =~ m/(.)(.)(??{ print "$1 - $2 "; if ($2 lt $1) { $ok = 0; print "Not Ok\n" } else { print "Ok\n"; }; 0 })/; print "Value of OK is $ok\n"; return $ok; } print "Sequence is ", in_sequence_debug($seq1)?"good":"bad", "\n"; print "-"x40, "\n"; print "Sequence is ", in_sequence_debug($seq2)?"good":"bad", "\n";
It seems that the value of my $ok has not been modified by the code $ok = 0 inside (??{ ... }).Value of OK is 1 a - a Ok a - b Ok b - c Ok c - d Ok d - e Ok e - f Ok f - g Ok Value of OK is 1 Sequence is good ---------------------------------------- Value of OK is 1 a - a Ok a - b Ok b - c Ok c - d Ok d - e Ok e - f Ok f - g Ok g - a Not Ok a - b Ok b - c Ok c - d Ok d - e Ok Value of OK is 1 Sequence is good
And this time, the output becomes -use strict; my $seq1 = 'aabcdefg'; my $seq2 = 'aabcdefgabcde'; my $ok; # moved up to the file scope sub in_sequence_debug { my $str = shift; $ok = 1; print "Value of OK is $ok\n"; $str =~ m/(.)(.)(??{ print "$1 - $2 "; if ($2 lt $1) { $ok = 0; print "Not Ok\n" } else { print "Ok\n"; }; 0 })/; print "Value of OK is $ok\n"; return $ok; } print "Sequence is ", in_sequence_debug($seq1)?"good":"bad", "\n"; print "-"x40, "\n"; print "Sequence is ", in_sequence_debug($seq2)?"good":"bad", "\n";
It actually worked when I move the $ok variable up one level to the file scope!Value of OK is 1 a - a Ok a - b Ok b - c Ok c - d Ok d - e Ok e - f Ok f - g Ok Value of OK is 1 Sequence is good ---------------------------------------- Value of OK is 1 a - a Ok a - b Ok b - c Ok c - d Ok d - e Ok e - f Ok f - g Ok g - a Not Ok a - b Ok b - c Ok c - d Ok d - e Ok Value of OK is 0 Sequence is bad
In reply to Variable scoping oddity inside (??{ ... }) by Roger
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |