Hi Simon,

thanks for helping Anirban, but I have a small comment about your code:

On Tue, 24 Mar 2015 13:11:56 +0100
Simon Reinhardt <si...@keinstein.org> wrote:

> Hi Anirban,
> 
> first we have to be clear how you want to sort the lines.
> Does 10-1 sort before 1-11 ?
> Do you want numeric (use <=>) or alphabetic (use cmp) order?
> 
> > while (my $line = <$RFH>) {
> >         chomp($line);
> >         if ($line =~ m/.*?\-(\d+)\-(\d+).*/) {
> >                 $sequence_no = "$1$2";
> >         #       print "$sequence_no-- $line\n";
> >                 $file_content_hash{$sequence_no}="$line";
> >         }
> > }
> 
> this will only work as long as the sequence numbers are unique. If two
> different lines have the same sequence number, the latter will be discarded.
> 
> My suggestion would be
> 
> #!/usr/bin/env perl
> use 5.010;
> use warnings;
> use strict;
> use autodie;
> my $file_name = "RXMOI_TRX_CMD";
> my @lines;
> 
> open(my $fh, "<", $file_name);
> 
> while(<$fh>) {
>     chomp;
>     if (/^RXMOI:MO=RXOTRX-([0-9]+)-([0-9]+)/) {
>       push @lines, [$_, $1, $2];
>     }
>     else {
>       warn("line '$_' does not match");
>     }
> }
> 
> my @sorted = sort {
> # if the numbers before the "-" are equal, compare the numbers after the "-"
> $a->[1] <=> $b->[1] ? $a->[1] <=> $b->[1] : $a->[2] <=> $b->[2]

This can be more idiomatically written as:

$a->[1] <=> $b->[1] or $a->[2] <=> $b->[2]

This is because in Perl (as opposed to in C and in other languages)
and/or/"||"/"&&" return the last true value instead of just 0 or 1. As a
result, using "or" for chaining comparators is a common Perl idiom.

> }
> @lines;       
> 
> say $_->[0] for @sorted;
> 

Regards,

        Shlomi Fish


-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Funny Anti-Terrorism Story - http://shlom.in/enemy

Chuck Norris doesn't celebrate holidays -- holidays celebrate Chuck Norris.
(By sevvie: http://sevvie.github.io/ .)
    — http://www.shlomifish.org/humour/bits/facts/Chuck-Norris/

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/


Reply via email to