PERL : Sort substring occurrences in array of strings

Hi,

My developer is on vacation and I am not sure if there is something which is easier for this.

I have an array of strings. Each string in the array has "%" characters in it. I have to get the string(s) which have the least number of "%" in them.

I know how I can get occurrences :

 
my @str;
...array population here...
my $count = ($str =~ tr/"%"//);

But I am not sure what is the best way to get the string(s) with least number of "%"'s.

Any advise/help is highly appreciated.

Thanks.

Warning: the following is an example of how (positively) twisted Perl is:

$least = ( sort { my $oa = $a =~ s/(%)/$1/g; my $ob = $b =~ s/(%)/$1/g; $oa <=> $ob } @str )[0];

This will put the string with the least amount of '%' in $least.

perl -le'

@a = qw(
  a%b%
  ab%%%a%b
  b%%%ab
  );
  
print join $/, 
  map $_->[1], 
    sort { 
      $a->[0] <=> $b->[0] 
      } map [ tr/%//, $_ ], 
        @a;
  '  

Output:

% perl -le'

@a = qw(
  a%b%
  ab%%%a%b
  b%%%ab
  );

print join $/,
  map $_->[1],
    sort {
  $a->[0] <=> $b->[0]
  } map [ tr/%//, $_ ],
    @a;
  '  
a%b%
b%%%ab
ab%%%a%b

And yet another -

$
$
$ perl -le '@str = qw( %%abc %ab%c% %a%b%c% ab%c ab%%%%%c ab%%c );
            for (@str) {$x=$_; $count=s/%//g; if (!defined $min or $count<$min){$min=$count; $elem=$x}}
            print "\nElement with the least number of % character => ",$elem'
 
Element with the least number of % character => ab%c
$
$

tyler_durden

1 Like

Yep,
my post was based on the subject line.
Actually, in this case, the sort could be avoided and your solution is more efficient and appropriate.

Thank to all who responded. :slight_smile:
Appreciate your help.

I have just one issue with the approach given -
As indicated in the original post I need the string(s) (string or strings) having the least number of %'s.

Please advise/suggest on having the list of strings/string which have/has the least number of %'s.

perl -le'
  @str = qw( 
  ab% %%abc %ab%c% %a%b%c% ab%c ab%%%%%c ab%%c 
    );
  
  do {
    $cnt = tr/%//; push @{$cnt{$cnt}}, $_;
    $min = $cnt unless defined $min and $cnt > $min;
      }
    for @str;  
  print "Element(s) with the least number of % character => ", 
    join ", ", @{$cnt{$min}};
  ' 

Output:

% perl -le'
  @str = qw(
  ab% %%abc %ab%c% %a%b%c% ab%c ab%%%%%c ab%%c
    );

  do {
    $cnt = tr/%//; push @{$cnt{$cnt}}, $_;
    $min = $cnt unless defined $min and $cnt > $min;
      }
    for @str;
  print "Element(s) with the least number of % character => ", join ", ", @{$cnt{$min}};
  '
Element(s) with the least number of % character => ab%, ab%c
1 Like

Thanks a TON. :slight_smile:
This helped.