[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 407
  • Last Modified:

Perl Sort Regex

I have the task of sorting a list - not a problem
@groupoptions = sort { $a->[1] cmp $b ->[1]} @groupoptions;

what I have to do is then remove the word "The" from the sort and sort on the second word of the list.

Is there a way of doing it with a regex within the sort where I could use something like $string =~ s/The//g;  ?
I would have values like:
company10
company1
The company7
The company 6

etc...
0
BalNigel
Asked:
BalNigel
1 Solution
 
mjcoyneCommented:
#!/usr/bin/perl -w
use strict;

my @original = (
    'company10',
    'company1',
    'The company7',
    'The company 6',
);

my @sortable;

for (@original) {
    push @sortable, ($_ =~ /(?:^The\s)?(.+)/);
}

@sortable = sort {$a cmp $b} @sortable;

print join "\n", @sortable;
0
 
BalNigelAuthor Commented:
This is what I did eventually - was trying to be very lazy initially, but I will take the regex, it's useful.
foreach my $company_value (@groupoptions){
      company_value->[1] =~ s/The //;      
}

@groupoptions = sort { $a->[1] cmp $b ->[1]} @groupoptions;
0
 
ozoCommented:
@groupoptions = (
["c","company10"],
["b","company1"],
["d","The company7"],
["a","The company 6"],
);
@groupoptions = map{$_->[0]}
                sort {$a->[1] cmp $b->[1]}
                map {[$_,($_->[1]=~/^(The\s+)?(.*)/i)[1]]}
                @groupoptions;
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now