简体   繁体   中英

Sorting characters in string by the vowels using Perl

I need to sort lowercase strings based on the vowels appearing in the given strings that are inputted from a file. I need to print the sorted list of strings on the command prompt.

ie the vowel will be the substring of vowels appearing in stringA (vowelA), and vowelB the corresponding substring of stringB. StringA appears before stringB in the output if the substring vowelA appears before vowelB in the ascending ASCII order.

What I have currently:

 #!/usr/bin/perl -w

use warnings;
use strict;

open my $INFILE, '<', $ARGV[0] or die $!;

while( my $line = <$INFILE> ) {

sub sort_vowels {

 my $vowels_a = $a;
 my $vowels_b = $b;

$vowels_a =~ s/[^aeiou]//g;     # only vowels
$vowels_b =~ s/[^aeiou]//g;

return $vowels_a cmp $vowels_b;   # compare the substrings
}
}

print sort { sort_vowels };     # print the sorted strings

close $INFILE;

Sample Input:

albacore
albatross
vermeil
panacea
apparate
parmesan
candelabra
fanfare   
false    
beans 

This should output:

apparate
fanfare
panacea
albatross
albacore
false
parmesan
candelabra
beans
vermeil

The error I'm getting:

syntax error at sort_strings.pl line 22, near "};"
Execution of sort_strings.pl aborted due to compilation errors.

Not sure where I went wrong. Any help would be greatly appreciated!

Perhaps print sort { sort_vowels } <$INFILE>; is what you're looking for.

while and foreach loops allow you to work with a single element at a time, but sort requires an entire list as it's input.

Well, if you consider a vowels-only version of the string a key to the sort order of the words, then you can process each word like so:

push @{ $hash{ lc ( $word =~ s/[^aeiou]//igr ) } }, $word;

Starting with Perl 5.14 the /r flag returns the result. Same could be done this way, pre-5.14:

push @{ $hash{ lc( join( '', $word =~ m/([aeiou]+)/ig )) } }, $word;

Then outputting the order is only a matter of getting a sorted set of keys and dereffing the list of words stored within those keys:

say foreach map { @{ $hash{ $_ } } } sort keys %hash;       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM