An enlightening ex-vivo demonstration of Perl internals:
use strict; my @list = 0..9; print "Step 1: @list\n"; alias_fun(@list); sub alias_fun { splice @_, 5, 5, 0..4; $_ = 'X' for @_; print "Step 2: @_\n"; } print "Step 3: @list\n";
Mondo ++ to whomever can guess the SoPW question that inspired the pathological code above.

Replies are listed 'Best First'.
Re: Aliases upon aliases
by dragonchild (Archbishop) on Sep 29, 2004 at 12:30 UTC
    I'm not quite sure what you're getting at. You could replace 0..4 with 'a'..'e' and you'll get the same answer. You're essentially "protecting" the second half of the list by writing on it with new values using splice (which doesn't trigger the aliases because it operates on lists, not scalars) and then writing on the other half by dealing with the scalars.

    The "trick", as it were, is the fact that @_ isn't an alias itself; its elements are aliases.

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

      Yes, the 0..4 was not the point; I simply needed to overwrite it with a 5-element list with any values. My reason for posting this was exactly the "trick" you noted, and the fact that splice does not involve the aliases, even when overwriting.
Re: Aliases upon aliases
by demerphq (Chancellor) on Sep 29, 2004 at 16:10 UTC

    I like this one better:

    package Printable; use overload '""'=>sub { shift->() }; package main; sub make_printer{ my ($fmt)=shift; my $args=\@_; bless sub { sprintf $fmt,@$args },'Printable'; } my ($x,$y,$z); my $formatted=make_printer("%5d %5d %f\n",$x,$y,$z); while (++$x<10) { $y=$x**2; $z=1/$x; print $formatted; }

    Aliases are your friend in Perl... :-)


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi

      Flux8


Re: Aliases upon aliases
by calin (Deacon) on Sep 29, 2004 at 12:35 UTC
    An enlightening ex-vivo demonstration of Perl internals:

    Don't you think that is a bit of an overstatement?