fenonn has asked for the wisdom of the Perl Monks concerning the following question:

I have a scalar varible storing data seperated by commas and newline characters. An example of that data would be something like:

John,Doe,Pine St,12345
Jane,Doe,Aspen Way,45678
Andy,Smith,Park St,79845

I use the following command to convert that data into a 2d array.
my @temp = map { [split /,/] } (split/\n/,$data);
after converting the data into a 2d array I would extract only the last names into an array. I would do something like this.
my @lastNames; for my $i ( 0..$#temp) { push @lastName, $temp[$i][1]; }

I wanted to know if there was a way to skip the step of converting the scalar into a 2d array and go straight to the single array of the data I need. Any help I can get would be great.

Replies are listed 'Best First'.
Re: Extracting data from a 2D array
by arturo (Vicar) on Jun 08, 2001 at 02:17 UTC

    In a single line ...

    my @lastnames = map { (split ",")[1] } split "\n", $scalar;

    Uses an array slice; the map returns the second element of each line.

    HTH!

    perl -e 'print "How sweet does a rose smell? "; chomp ($n = <STDIN>); +$rose = "smells sweet to degree $n"; *other_name = *rose; print "$oth +er_name\n"'
(ar0n) Re: Extracting data from a 2D array
by ar0n (Priest) on Jun 08, 2001 at 11:58 UTC
    Yet another way to do it is:
    push @lastnames, map { $_->[1] } map { [ split "," ] } while (<FH>);
    I'm assuming that with "scalar variable storing data" you mean a filehandle.

    ar0n ]

Re: Extracting data from a 2D array
by bikeNomad (Priest) on Jun 08, 2001 at 03:25 UTC
    Sure, use the m//m operator/modifier:
    my @lastNames = $data =~ m{^[^,]+,([^,]+)}gm;
    This gets the second field from each line.
Re: Extracting data from a 2D array
by tachyon (Chancellor) on Jun 08, 2001 at 02:34 UTC

    You can do it like this

    tachyon

    my @names = map{/,([^,]+)/}(<DATA>); print "@names"; __DATA__ John,Doe,Pine St,12345 Jane,Doe,Aspen Way,45678 Andy,Smith,Park St,79845