Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Sorting numerials first and then numerials with alpha characters last

by hippo (Bishop)
on Oct 29, 2021 at 13:43 UTC ( [id://11138211]=note: print w/replies, xml ) Need Help??


in reply to Sorting numerials first and then numerials with alpha characters last

Code is slopppy. Just learning.

That's fine - I will leave most of your code as it stands and put a Schwartzian Transform into your sort line. This produces your specified output - let's hope that's representative. :-)

require 5.000; use warnings; use strict; use POSIX; my %tags = (); my $input = $ARGV[0]; my $output = $ARGV[1]; open (FILE, "< $input") or die "cannot open $input: $!\n"; while (my $tag = <FILE>) { $tag =~ m/<t id=(\d*)(.*)((\d*)([[:alpha:]]*))>/; if ($tag eq "\n") { # BLANK LINE } else { $tag =~ m/<t id=\((\d*)(.*)((\d*)([[:alpha:]]*))\)>/; $tags{sprintf("%04d%6s",$1 || 9999,$2)} = $tag; } } close FILE; open (NEWFILE, "> $output") or die "cannot open $output: $!\n"; foreach my $id ( map { $_ = $_->[2] } sort { $a->[1] cmp $b->[1] || $a->[0] <=> $b->[0] } map { /(\d+)([a-z]*)/; $_ = [$1, $2, $_] } keys %tags ) { print NEWFILE $tags{$id}; print $tags{$id}; } close NEWFILE;

🦛

  • Comment on Re: Sorting numerials first and then numerials with alpha characters last
  • Download Code

Replies are listed 'Best First'.
Re^2: Sorting numerials first and then numerials with alpha characters last (named captures)
by LanX (Saint) on Oct 29, 2021 at 19:14 UTC
    not sure why you assign to $_ here ...

    >  $_ = [$1, $2, $_]

    But I felt tempted to try a variation with named captures for clarity. (tests borrowed from Hauke's post)

    use strict; use warnings; use Data::Dump; use Test::More; my @in = ( "2bc", "1", "12c", "12", "21", "1", "1a", "2", "2", "2", "2", "3", "35", "31", "2b", "4", "42", "5", "51", "2ac", "52", "6", "7" ); my @exp = ( "1", "2", "3", "4", "5", "6", "7", "12", "21", "31", "35","42", "51", "52", "1a", "2ac", "2b", "2bc", "12c", ); my %in; @in{@in}=(); # unique my @got = map { $_->{orig} } sort { $a->{alpha} cmp $b->{alpha} || $a->{num} <=> $b->{num} } map { /(?<num>\d+)(?<alpha>[a-z]*)/; { orig => $_, %+ } } keys %in; is_deeply(\@exp,\@got) or ddx [\@exp,\@got]; done_testing;

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11138211]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-04-23 23:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found