in reply to Using x to build data structures considered harmful

I've been bitten by that before. And that's not all 'x' does that can be evil:
my $x = 10; foo(($x) x 2); print "x = $x\n"; sub foo { $_[0]++; $_[1]++; print "@_\n"; }
You might not expect the results you get.
_____________________________________________________
Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

Replies are listed 'Best First'.
Re^2: Using x to build data structures considered harmful
by theorbtwo (Prior) on Jul 17, 2004 at 18:06 UTC

    To amplify a bit: The original used x twice. Only one of them was evil. Note that the best WTDI may be:

    my $matrix; { my @row = (0) x $width; $matrix = [map {[@row]} 1..$height]; }

    OTOH, the most perlish way to do it is probably just my $matrix;, and letting perl autovivify the rest when it's created. I assume that dws had a reason to not do that, though.


    Warning: Unless otherwise stated, code is untested. Do not use without understanding. Code is posted in the hopes it is useful, but without warranty. All copyrights are relinquished into the public domain unless otherwise stated. I am not an angel. I am capable of error, and err on a fairly regular basis. If I made a mistake, please let me know (such as by replying to this node).

Re^2: Using x to build data structures considered harmful
by ihb (Deacon) on Jul 17, 2004 at 20:18 UTC

    I admit. I don't get it. :-)

      foo(($x) x 2)

    is supposed to be a lazy way to do

      foo($x, $x)

    right? How is that evil? They will both give the same results (i.e. that $x is 12 after the call). What might one expect instead? Is my translation incorrect?

    The thing you get bitten by here is just the aliasing, not the x operator as I understand it.

    Update: Ah, got it. My translation was incorrect (because it actually was a correct translation). Seems like Perl does good dwim in this case, with the i meaning ihb. :-)   ($x) x $n in list context could be believed to be equivalent to

    map $x => 1 .. $n # or sub { ($x) x $n } -> ()
    which both return copies of the values and the output would then be
    11 11 10
    Good thinking, japhy.

    ihb

      It's the fact that it's not making copies, it is making aliases. The subroutine's aliasing is another layer, but the fact that 'x' doesn't make copies is the primary thing here.
      _____________________________________________________
      Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
      How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart