0

I am attempting to write a script that will take both a string and a single character from the command line, and then search the string for the single character for the number of occurrences. I have attempted to do this by making the string into an array and looping through each individual element of the array, but I get 0 every time I try to do this. Is converting the string to the array of single characters possible or should I try a new method?

use strict;
use warnings;    
if ($ARGV[0] eq '' or $ARGV[1] eq '') {
        print "Usage: pe06f.pl string char-to-find\n";
        exit 1;
}
my $string = $ARGV[0];
my $searchChar = $ARGV[1];
if (length($searchChar) > 1) {
        print "Second argument should be a single character\n";
        exit 2;
}
my @stringArray = split /\./,$string;
my $count = 0;
$i = 0;
for ( $i=0; $i <= length($stringArray); $i++) {
        if ( $stringArray[$i] eq $searchChar) {
                print "found $b at position $i";
                $count++;
        }
}
print "found $count occurrences of $searchChar in $string\n";

1 Answer 1

1

You could try this:

#!/usr/bin/perl

use warnings;
use strict;

my ($str, $chr) = @ARGV;

my $cnt = () = $str =~ m/$chr/g;
print "$cnt\n";

Explanation:

$cnt = () = $str =~ m/$chr/g will find out how many matches of character $chr there are in string $str, here is how it achieves that:

  1. $str =~ m/$chr/g will do a global pattern matching (/g), and
  2. () = ... will put that pattern matching in list context,
  3. therefore it will return a list of all the matched strings,
  4. finally the $cnt = ... will put that list in scalar context,
  5. so the value of $cnt will be the number of element in that list.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.