Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Problems with strings

by thanos1983 (Parson)
on May 20, 2019 at 13:26 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11100284]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2024-04-24 10:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found