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

Hello all. I am not new to unix, but very new to perl. I have a nifty little script set up that finds people with an ID of 100,1000,10000 you get the point, but I am now trying to sort it alphabetically by last name and I am running into all kinds of snags, here is the scrpt any help would be appreciated

#!/usr/bin/perl -w use strict; my ($ID, $DP, $LN, $FN, $NM); open(EMPLOYEES,"<employees") || die "Cannot Open"; while(<EMPLOYEES>) { if(/(.*):(1.*):(.*):(.*):(.*)/) { #Supposed to parse $_ $ID = $1; $DP = $2; $LN = $3; $FN = $4; $NM = $5; print $ID; # print $DP; # print $LN; # So I can see if a value is there print $FN; # print $NM; # chomp; (my @f = split(/:/)) == 5 or next; print join("\t", @f[2, 3, 0, 4]), "\n"; } } close(EMPLOYEES)

Replies are listed 'Best First'.
Re: Quick Sort Question
by zwon (Abbot) on Dec 09, 2009 at 20:23 UTC

    Something like this should work (not tested!):

    use strict; use warnings; open my $fh, "<", "employees" or die "Cannot Open: $!"; my @employees; while (<$fh>) { chomp; if (/(.*):(1.*):(.*):(.*):(.*)/) { push @employees, [ $1, $2, $3, $4, $5 ]; } } close $fh; @employees = sort { $a->[2] cmp $b->[2] } @employees; for (@employees) { print join( "\t", @$_[ 2, 3, 0, 4 ] ), "\n"; }

    Update: bug fixed

      I am getting an uninitialized value in join error if I try it the way you have it.

        Try  @$_[ 2, 3, 0, 4 ]

        (the for loop aliases individual arrayrefs to the default variable $_, which you need to dereference and slice)

        I warned that it's not tested, and the reason is that you didn't provide us with test input ;) I fixed the problem, that should be @$_[...] instead of @_[...]

Re: Quick Sort Question
by baxy77bax (Deacon) on Dec 09, 2009 at 20:30 UTC
    well if you can afford to store the data in memora this could work for you
    use strict; my @array; while(<DATA>){ chomp; my @arr = split(',',$_); push (@array,\@arr); } @array = sort{$a->[1] cmp $b->[1]}@array; foreach (@array){ print "@$_ \n"; } __DATA__ miki,maus,kiki sis,miki,misi nick,pick,flick amico,aco,taco