in reply to Re^2: Arrays merges and redundancies
in thread Arrays merges and redundancies
List::Util is a core module (no installation required) - you will have to install List::MoreUtil if you want to use it. Besides being very handy functions, they are fast because they are implemented in C.
update: notice that keys %h does not come out in any particular order - make @uniqIDs and use that array to enforce the ordering of the data to be like in the original when you print it out - and this will wind up being faster than doing multiple "sort keys %h" anywayuse strict; use warnings; use Data::Dumper; my @IDs = qw(Apple Apple Grape Banana Banana); my @Price = qw(5 5 2 3 4 ); my @Amount = qw(10 15 3 4 4 ); sub uniqjoin { my $sep=shift; my %seen; return join($sep, grep { !$seen{$_}++ } @_); #NO SORT } my %h; #to hash of array my $idx =0; foreach my $id (@IDs) { push @{$h{$id}->{price}} , $Price[$idx]; push @{$h{$id}->{amount}}, $Amount[$idx]; $idx++; } #concatenate arrays with '/' foreach my $id (keys %h){ $h{$id}->{price} = uniqjoin( '/', @{$h{$id}->{price} } ); $h{$id}->{amount} = uniqjoin( '/', @{$h{$id}->{amount}} ); } my %seen; my @uniqIDs = grep{!$seen{$_}++}@IDs; #print print join(' ', @uniqIDs) . "\n"; print join(' ' , map{ $h{$_}->{price} } @uniqIDs ) . "\n"; print join(' ' , map{ $h{$_}->{amount} } @uniqIDs ) . "\n"; __END__ Apple Grape Banana 5 2 3/4 10/15 3 4
There is some redundancy in the code, you could make your own uniq() function like the one in List:MoreUtil and use in join() - but why bother? Use the module and get the advantage of well debugged, fast code (should run faster than a pure Perl implementation). Of course there are some scalability/re-usability issues too - due to hard coding of price and value - but if this meets your needs - go for it!
If you use a Perl 5.12 feature like the each() function for arrays, I would put a "use 5.012;" statement in the code. Many people like me are still at 5.10.1.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Arrays merges and redundancies
by remiah (Hermit) on Mar 31, 2012 at 13:45 UTC | |
|
Re^4: Arrays merges and redundancies
by Anonymous Monk on Mar 31, 2012 at 10:27 UTC | |
|
Re^4: Arrays merges and redundancies
by Anonymous Monk on Mar 31, 2012 at 10:49 UTC |