Aman Cgiperl wrote:
> 
> Execute the following on cmd line as follows
> $./cnt.pl <string> ,
> You can replace the comma (,) on the command line to find any other
> character's occurrence in the string
> _______________________
> #!/usr/bin/perl
> 
> for(;$i<length($ARGV[0]);$i++)  {
>         $str[i] = substr($ARGV[0],$i,1);
>         if($str[i] eq $ARGV[1]) {
>                 $cnt++;
>         }
> }
> print $cnt;
> -----------------------
> Aman
> 
> PS: I am just a novice, so there might be quicker ways I yet don't know
> of !!!

Hi Aman.  No offense but that looks more like C than Perl.  Why are you
using an array (@str) to store the current character instead of a
scalar?

for ( ; $i < length( $ARGV[0] ); $i++ ) {
    $str = substr( $ARGV[0], $i, 1 );
    if ( $str eq $ARGV[1] ) {
        $cnt++;
    }
}
print $cnt;


As a matter of fact, why not just use the substr in the comparison?

for ( ; $i < length( $ARGV[0] ); $i++ ) {
    if ( substr( $ARGV[0], $i, 1 ) eq $ARGV[1] ) {
        $cnt++;
    }
}
print $cnt;


And of course we can make the for statement more perl-like.

for ( 0 .. length( $ARGV[0] ) - 1 ) {
    if ( substr( $ARGV[0], $_, 1 ) eq $ARGV[1] ) {
        $cnt++;
    }
}
print $cnt;


And if you really want to get cute you can put it all on one line:

substr( $ARGV[0], $_, 1 ) eq $ARGV[1] and $cnt++ for 0 .. length(
$ARGV[0] ) - 1;
print $cnt;


:-)

John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to