in reply to Re: Re: How can I read multiple lines starting with the same number and put in to a nested array and print it to a file?
in thread How can I read multiple lines starting with the same number and put in to a nested array and print it to a file?

This is untested and bad Perl (I'm new to it) but the algorithm should be clear and work ok. If your lucky, one of the experts here will be so appalled by my Perl that he will step in a clean it up or offer you better.

# somewhere to remember the records we processing my $lastFirstNum = ""; my @nums; # work array while (<>) { # get the first number from the line my $firstNum = split /\s/, $_, 1; # prime the pump if its the first time through $lastFirstNum = $firstNum if $lastFirstNum = ""; if ( $firstNum eq $lastFirstNum ) { # its still the same type so save it push @nums, $_; next; # skip to next record } # we found the last one sort the array @nums = map {[ reverse sort @$_ ]} @nums; #open output using the first number as the name open( FH, ">$lastFirstNum" ) or die "Can't open $lastFirstNum: $!" +; print @nums; close( FH ) or die "Couldn't close $lastFirstNum: $!"; # the number changed $lastFirstNum = $firstNum; undef @nums; #clean the array push @nums, $_; # push the new record }

Update: corrected my own (first) obvious mistake.

  • Comment on Re: Re: Re: How can I read multiple lines starting with the same number and put in to a nested array and print it to a file?
  • Download Code