Sort strings based on the character contained in the string

I have a text file containing a list of lines that I want to sort based on the first number contained in the line. If the string does not contain a number, then ignore it.

For instance:

string1
string2
another_string1
another_string2

I want to sort above:

string1
another_string1
string2
another_string2
0
source share
2 answers
@strings = qw/
    string1
    string2
    another_string1
    another_string2
/;
my @sorted_strings =
    map { $_->[0] }
    sort { $a->[1] <=> $b->[1] }
    map { /(\d+)/ ? [ $_, $1 ] : () }
    @strings;
+4
source
#!/usr/bin/perl

use strict;

my @strings = qw/
    string1
    string2
    another_string1
    another_string2
/;

my %h;

foreach my $string (@strings) {
    if ($string =~ /(\d+)/) {
        push @{$h{$1}}, $string;
    } else {
        print "cannot classify $string : skipping\n";
    }
}

foreach my $key (sort { $a <=> $b } keys %h) {
    foreach my $s (@{$h{$key}}) {
        print $s . "\n";
    }
}

More detailed than ysth solution , but I hope this helps. Essentially: I use a hash %hwhere the keys are numbers (matching the end of lines), and the values ​​are arrays containing strings ending with that number. After creating the hash, I will print its contents, sorting the keys (i.e. the numbers at the end of your lines).

+1
source

Source: https://habr.com/ru/post/1693849/


All Articles