in reply to Re: Arrays manipulation
in thread Arrays manipulation

Easier to read and avoids the map in void context:

#!/usr/bin/perl my @array = ( 'nfs,7,rw', 'afp,12,rro', 'cifs,32,ro', 'dns,5,rw', ); my @cols; for my $row (@array) { my $i = 0; push @{$cols[$i++]}, $_ for split /,/, $row; } use Data::Dumper; print Dumper(\@cols);

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re^3: Arrays manipulation (no $i either)
by Aristotle (Chancellor) on May 02, 2003 at 00:56 UTC
    And without an explicit counter variable:
    my @cols; for my $row (@array) { my @f = split /,/, $row; push @{$cols[$_]}, $f[$_] for 0 .. $#f; }

    Makeshifts last the longest.

      Six of one, half a dozen of the other. You made the array explicit, I made the counter explicit. Personally, I prefer for split /,/, $row because it keeps the meat all on one easy-to-eat line. I'm also comfortable enough with C to be happy with the autoincrementing counter.

      Didja benchmark them? (Kidding, of course.)

      -sauoq
      "My two cents aren't worth a dime.";
      

        I'm not sure, but pretty certain that your version is more efficient, and you're also right that I traded one variable for another.

        The reason I prefer the version I posted is another, though: it has one less side effect. (I tried to do without the push too, but no practicable solution presented itself.) The fewer side effects, the more decoupled things become - f.ex, try changing your version such that it inserts an element from a different data source into a column determined by one of the fields of $row. That's a trivial change for the code I posted.

        Makeshifts last the longest.