Hi Chris, On Sunday 20 Mar 2011 05:43:38 Chris Stinemetz wrote: > I am trying to code a foreach loop, that will add all occurrences of the > element rlptxat that have the same elements cell, sect and chan. > > My failed attempt can be located in between the ### lines. >
If I understand your code correctly, then you should somehow serialise those into the same hash key (possibly using Storable.pm/JSON/etc.). Don't use the old $my_hash{$key1, $key2, $key3} notation. You may also opt to construct a hash of hashes. Now a few other comments: > Below is what I have so far. > > Thank you in advance, > Chris > > #!/usr/bin/perl > > use warnings; > use strict; > use File::Slurp; > my $filepath = 'C:/temp/PCMD'; > my $output = 'output.txt'; > You should add some empty lines here: http://perl-begin.org/tutorials/bad-elements/#paragraphs > my %cols = ( > cell => 31, > sect => 32, > chan => 38, > dist => 261, > precis => 262, > rlptxat => 44, > ); > > my @records; > > my @lines = read_file( $filepath ); > > chomp @lines; > You should read the file line-by-line, using: < $fh > Not slurp it. > foreach my $line ( @lines ) { > > next unless $line =~ /;/; > my %record; > # this gets just what you want into a hash using a hash slice and an # > array slice. # the order of keys and values will be the same for any # > given hash > > @record{ keys %cols } = (split /;/, $line)[ values %cols ]; > #################################################################### > > > $record{rlptxat} = ( length($record{rlptxat})> 1 ) ? > $record{rlptxat}{cell, sect, chan, dist}++ : '' ; > > #################################################################### > > $record{carr} = > ( $record{chan} == 75 ) ? 2 : > ( $record{chan} == 1025 ) ? 2 : 1 ; > #1; # Common carrier > $record{dist} = ( length( $record{dist}) > 1 ) ? > $record{dist}/6.6/8/2*10/10 : '' ; > > push( @records, \%record ) ; > } > > my @sorted = sort { > $a->{cell} <=> $b->{cell} || > $a->{sect} <=> $b->{sect} || > $a->{carr} <=> $b->{carr} > } @records ; > > my @report = map > "$_->{cell}\t$_->{sect}\t$_->{carr}\t$_->{chan}\t$_->{dist}\n" , @sorted; > > > > print @report ; This map will consume a lot of memory, better do it using a foreach loop. Regards, Shlomi Fish > write_file($output, @report) ; -- ----------------------------------------------------------------- Shlomi Fish http://www.shlomifish.org/ My Favourite FOSS - http://www.shlomifish.org/open-source/favourite/ "You are banished! You are banished! You are banished! Hey! I'm just kidding!" Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/