Perl count characters from string

This program counts the characters from a string and print how many of each are available:

#!/usr/bin/perl
use strict;

str_stat("Live Free or Die");

sub str_stat {
    my $var = shift;
    my @arr = sort split'',lc($var);
    my $count = -1;
    my $last = '';
    
    for(@arr){
        if($last ne $_){
            if($count == -1){
                print "'$_':";
            }else{
                print "$count\n'$_':";
            }
            $last = $_;
            $count= 1;
        }else{
            ++$count;
        }
    }
    print "$count\n";
}

Our result:

' ':3 
'd':1 
'e':4 
'f':1 
'i':2 
'l':1 
'o':1 
'r':2 
'v':1

he counts everything included white spaces and special chars.

Leave a Reply

Your email address will not be published.

fifteen − 12 =