Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Problems with strings

by thanos1983 (Parson)
on May 20, 2019 at 13:26 UTC ( #11100284=note: print w/replies, xml ) Need Help??


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!

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11100284]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2020-05-29 11:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (169 votes). Check out past polls.

    Notices?