Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How can I group lines in a file?

by johngg (Canon)
on May 16, 2009 at 23:10 UTC ( [id://764461]=note: print w/replies, xml ) Need Help??


in reply to How can I group lines in a file?

zwon has pointed you in the right direction but I note that your output is not sorted by name but retains the order in which names first occured in the data. To keep that order you will need to preserve it in the hash and sort on it when printing.

use strict; use warnings; my $order = 0; my %names = (); while( <DATA> ) { my( $name, $value ) = split; $names{ $name }->{ order } = ++ $order unless exists $names{ $name }; push @{ $names{ $name }->{ values } }, $value; } print do { local $" = q{,}; qq{$_ @{ $names{ $_ }->{ values } }\n}; } for sort { $names{ $a }->{ order } <=> $names{ $b }->{ order } } keys %names; __END__ jim 14 john 23 ernest 38 matilda 43 jim 34 ernest 27 john 44 matilda 22

The output.

jim 14,34 john 23,44 ernest 38,27 matilda 43,22

I hope this is of interest.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: How can I group lines in a file?
by zwon (Abbot) on May 17, 2009 at 07:45 UTC

    Just want to note that you can get the same order if you sort by name length or by first value ;)

    use strict; use warnings; my %res; while (<DATA>) { my ( $name, $weight ) = split /\s+/; push @{ $res{$name} }, $weight; } for ( sort { length($a) cmp length($b) } keys %res ) { print "$_ ", join( ",", @{ $res{$_} } ), "\n"; } for ( sort { $res{$a}->[0] <=> $res{$b}->[0] } keys %res ) { print "$_ ", join( ",", @{ $res{$_} } ), "\n"; } __DATA__ jim 14 john 23 ernest 38 matilda 43 jim 34 ernest 27 john 44 matilda 22

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://764461]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2026-03-09 09:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.