in reply to Problems with strings
Hello baxy77bax,
If I understand correctly your question and desired output one possible way is:
#!/usr/bin/perl use strict; use warnings; use feature 'say'; sub groupWithEachString { my %hash; $hash{$_}++ for (split //, shift); my $str; foreach my $character (sort keys %hash) { $str .= $character x $hash{$character}; } return $str; } my $str = "aaabbbabc"; say groupWithEachString($str); __END__ $ perl test.pl aaaabbbbc
Regarding your second question on how to repeat the process for multiple strings (simply concatenate the strings):
#!/usr/bin/perl use strict; use warnings; use feature 'say'; sub groupWithEachString { my %hash; $hash{$_}++ for (split //, shift); my $str; foreach my $character (sort keys %hash) { $str .= $character x $hash{$character}; } return $str; } my @strings = qw(aaabbbabc aaabbbabc); my $concatString; foreach my $string (@strings) { $concatString .= $string; } say groupWithEachString($concatString); __END__ $ perl test.pl aaaaaaaabbbbbbbbcc
Update: Last part (replace character in a string):
#!/usr/bin/perl use strict; use warnings; use feature 'say'; sub groupWithEachString { my %hash; $hash{$_}++ for (split //, shift); my $str; foreach my $character (sort keys %hash) { $str .= $character x $hash{$character}; } return $str; } my @strings = qw(aaabbbabc aaabbbabc); my $concatString; foreach my $string (@strings) { $concatString .= $string; } my $final = groupWithEachString($concatString); say $final; # Replace character in string $final =~ tr/a/z/; say $final; __END__ $ perl test.pl aaaaaaaabbbbbbbbcc zzzzzzzzbbbbbbbbcc
Hope this helps, Thanos.
Seeking for Perl wisdom...on the process of learning...not there...yet!
In Section
Seekers of Perl Wisdom