I am trying out different scripts in PERL. I want to take a line/string as an input from the user and count the number of occurrances of all the alphabets (a..z) in the string. I tried doingit like this :
#! /opt/exp/bin/perl
print "Enter a string or line : ";
$string = <STDIN>;
chop $string;
$string =~ tr/[A-Z]/[a-z]/; #print@string;
print "\n"; @arr = ('a' .. 'z');
foreach $val (@arr)
{
$count = ($string =~ tr/$val//);
print "$val occurred $count times\n";
}
But looks like I am going wrong somewhere. Please guide me to solve this.
I know this is an older thread, but I had a slightly different scenario, where I needed non-destructive counting and thought I'd share.
The s///g and tr/// methods already mentioned remove text from the original string. With a slight modification (adding parentheses and $1), the s/// operator can be used non-destructively:
$count = $string =~ s/([a-zA-Z])/$1/g;
In my specific case, I needed to sort a list of directories by depth. That is: /, /onelevel, /two/levels, /three/level/path, etc.
It sorts the list by the number of times "/" appears in the directory, which (on a Unix system) is the same as the depth. The sort function is able to obtain the counts repeatedly and still have the original strings left over.
Note that my code doesn't correctly handle doubled slashes (e.g. "/my//dir") or relative paths (e.g., "../dir" or "/my/dir/../dir2"), but it's easy to handle those by ensuring that the paths are all absolute prior to the above line of code.