0

So I have this Perl Script which is a word frequency counter. But now I have to modify this script and make it case sensitive. So if a user adds -i on the command line, the script should compare in a case-sensitive way. If the -i is not entered on the command line, it should compare in the old case-sensitive way.

Here is the script:

#!/usr/bin/perl

#words hash
my %words;

while( my $a = <> )
{
    chomp $a;
    foreach my $word ( split ( /\s+/, $a ))
    {
        $words{$word}++;
    }
}

foreach $word (keys %words)
{
    print "<$word> appears $words{$word} times\n";
}
1

1 Answer 1

0

You'll want to use Getopt::Std to help you with your option parsing, and set $case_insensitive to 1 if -i is given.

And then

foreach my $word ( split ( /\s+/, $a ))
{
    if ($case_insensitive) 
    {
        $words{lc $word}++;
    }
    else
    {
        $words{$word}++;
    }
}

or, more tersely

foreach my $word ( split ( /\s+/, $a ))
{
    $words{$case_insensitive ? lc $word : $word}++;
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .