On Aug 26, 12:25 pm, shlo...@shlomifish.org (Shlomi Fish) wrote: > ... > The problem starts to happen when you try to declare $a and $b using my. This > program: > > [CODE] > #!/usr/bin/perl > > use strict; > use warnings; > > my $a = 5; > my $b = 6; > > print map { "$_\n" } sort { $a <=> $b } (9,100,5,6,70,3,4,98,28,27); > [/CODE] > > Yields this error: > > [CODE] > Can't use "my $a" in sort comparison at test.pl line 9. > [/CODE] > > This is perl-5.14.1 - previous versions of Perl may behave more > erratically when executing this. $a and $b are built-ins plain and simple, and > should be treated as such, due to their use by perldoc -f sort and other > functions from List::Util, List::MoreUtils, etc.
The use of $a,$b elsewhere should definitely ring an alarm. Remembering: "use diagnostics qw/-verbose/ though makes the problem/solution very clear: (F) The global variables $a and $b are reserved for sort comparisons. You mentioned $a or $b in the same line as the <=> or cmp operator, and the variable had earlier been declared as a lexical variable. Either qualify the sort variable with the package name, or rename the lexical variable. Rob's follow-on remarks: ------------------------------ > > Overly-careful warnings can have the opposite of the desired effect, > > especially on beginner programmers, and make it seem like the language > > is rife with pitfalls and gotchas, especially when these apply to > > ubiquitous core concepts like $_. I hope people will think twice about > > the ideas that they are conveying. I tend to agree here that a cautionary -- rather than dogmatic -- tone is the better choice. -- Charles DeRykus -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/