sorting broken string

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

If a string is broken into pieces and sorted, with four components after
the string break, how would it be done.


@list = qw(CA2009000H1 AK2009000H2 FL2009000H1 FL2009000H13 FL2009000H111);

I would like the string to be broken like so:

$a =~ /^(\w)(\d+)([A-Za-z]+)(\d+)$/;

So we get  CA, 2009000, H, 1    etc.

The final sort should look like:


I was trying this for a sort block:
my @list = qw(AK2009000H2 CA2009000H1 FL2009000H1 FL2009000H13

@list = sort state_billnum @list;

sub state_billnum {
     $a =~ /^(\w)(\d+)([A-Za-z]+)(\d+)$/;
     my ($astt, $asession, $atype, $anum) = ($1, $2, $3, $4);
     $b =~ /^(\w)(\d+)(\w+)(\d+)$/;
     my ($bstt, $bsession, $btype, $bnum) = ($1, $2, $3, $4);
     $astt cmp $bstt ||
     $asession <=> $bsession ||
     $atype cmp $btype ||
     $anum <=> $bnum;

But this sorts as:


Re: sorting broken string

Quoted text here. Click to load it

Re: sorting broken string

Quoted text here. Click to load it

Ben Bullock solved it. But the explanation is..

\w includes numeric. Btype was grabbing all but
the last digit when $b is parsed (assuming just alpha
is needed).
Likewise, if you expect the state abbrv to
be all alpha, it should change as well.
Something like this.

  my ($astt, $asession, $atype, $anum) =
        $a =~ /^([a-z])(\d+)([a-z]+)(\d+)$/i;

  my ($bstt, $bsession, $btype, $bnum) =
        $b =~ /^([a-z])(\d+)([a-z]+)(\d+)$/i;


Re: sorting broken string

Thanks all, the improper RE will ruin a sort, thats for sure. It was too
late to be writing code i suppose ...

Quoted text here. Click to load it

Site Timeline