in reply to 2D arrays & mo' better blues

@alpha = 'a' .. 'z'; @outtie = ( [ @alpha ] ) x @alpha; foreach (@outtie) { print " $_ " foreach @$_; print "\n"; }

Or even more cryptic

@alpha = 'a' .. 'z'; @outtie = ( [ @alpha ] ) x @alpha; print join(' ', @$_) . "\n" foreach (@outtie)

--bwana147

Replies are listed 'Best First'.
Re: Re: 2D arrays & mo' better blues
by davorg (Chancellor) on Jun 06, 2001 at 18:47 UTC

    One slight caveat with the way you set up the array. You'll end up with 26 references to the same array. Depending on what you're doing with the data, this may or may not be a problem. All of the other solutions I've seen create a copy of the array each time.

    --
    <http://www.dave.org.uk>

    "Perl makes the fun jobs fun
    and the boring jobs bearable" - me

      updated update: update removed

      from perldoc perldsc

        The square brackets make a reference to a new array with a *copy* of what's in @array at the time of the assignment. This is what you want.

      @outtie = ( [ @alpha ] ) x @alpha; looks ok to me.

      "Argument is futile - you will be ignorralated!"

        Yes, the [@array] construct builds an array ref with a copy of the array --- But, the code in question uses the x operator to replicate a list of those references, and they will all be the same reference. Witness:

        my @list = (3,2,1); my @refs = ([@list]) x @list; print "@refs\n"; __END__ which prints: ARRAY(0x80f3764) ARRAY(0x80f3764) ARRAY(0x80f3764)

        Those are not references to the original array, they are all references to the same anonymous array that holds a copy of the original.

        It's true that square brackets make a reference to a new copy of the array. But the multiplication operator then takes 26 copies of that reference.

        I was originally going to post the same solution, but before I did, I checked it in the debugger :)

        --
        <http://www.dave.org.uk>

        "Perl makes the fun jobs fun
        and the boring jobs bearable" - me