in reply to Modify hash reference itself

The problem is that you are expecting $a to become an alias for $_[0]. It's not. It's simply a scalar holding a reference; the same reference as that held in $_[0]. Later, it becomes a scalar holding a reference to an anonymous hash. Consequently, it no longer is a scalar holding a reference to the same thing that $_[0] refers to.

On another note, $a is not necessarily a good choice for a lexical variable's name, as $a and $b also happen to be the special variables used by sort. It's not a problem in this case, but in some cases, it can lead to confusion and difficult to locate bugs.


Dave

Replies are listed 'Best First'.
Re: Re: Modify hash reference itself
by dragonchild (Archbishop) on Dec 02, 2003 at 00:46 UTC
    $a is not necessarily a good choice for a lexical variable's name

    Actually, to be completely pendantic, $a and $b are perfectly safe so long as you use an inline sort routine in the same scope. For example, this won't work:

    xyz(1 .. 5); sub xyz { my $a = shift; sort { $a <=> $b } @_; print "$a\n"; }
    But, the following will work:
    xyz(1 .. 5); sub xyz { my $a = shift; abc(@_); print "$a\n"; } sub abc { sort { $a <=> $b } @_; }
    Since abc() provides a different lexical scope than xyz(), everything is ok and $a within xyz() is safe.

    But, your point of confusion is still good, as single-letter variables are poor.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      Yea, I knew that $a and $b are not good choices, from writing sort code. I don't do that in my real code. But you guys are right to point that out when you see it of course.

      thanks