[Israel.pm] why did it happen

Gaal Yahas gaal at forum2.org
Wed Jun 20 10:36:09 PDT 2007

What everybody said, but also note there's something else going on. To
paraphrase the Tao Te Ching:

The $a that is assigned to is not the true $a :)

To see for yourself, rename the variable to $x:

    % perl -Mstrict -wle 'my $x = (27>20) ? $x = "big" : $x = "small"; print $x'
    Global symbol "$x" requires explicit package name at -e line 1.
    Global symbol "$x" requires explicit package name at -e line 1.
    Execution of -e aborted due to compilation errors.

What's going on?

You can't use $x until the my is in scope, which isn't until the next
statement. But $a, unfortunately, is exempt from this rule. Together
with $b, it's a special case to let you write things like

    @descending = sort { $b <=> $a } @list;

So, if your friend really had $a there, it's the wrong $a. It's a
package globan in whatever package they're in. And it can spell two
kinds of bugs; first, it might overwrite somebody else's value if they
use $a too, and second, if the sub this is in happens to close over
$a, it'll close over the lexical $a, the one declared by my and never
used elsewhere.

So: use strict, and avoid $a and $b. :-)

On 6/20/07, Yossi Itzkovich <Yossi.Itzkovich at ecitele.com> wrote:
> Hi,
> A college here wanted to write this code:
> my $a=(27>20)?"big":"small";
> And instead wrote:
> my $a= (27>20)?$a="big":$a="small");
> Surprisingly $a was set to "small".  Why ?
> Yossi
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl

Gaal Yahas <gaal at forum2.org>

More information about the Perl mailing list