Warm tip: This article is reproduced from stackoverflow.com, please click
perl regex scripting

Unexpected behaviour when reading parameters from standard input

发布于 2020-03-29 12:48:35
sub Solution{
    $matchflag=0;
    $occurence=0;

    #OUPTUT [uncomment & modify if required]
    my $ind=index($m,$p);


    if ($ind!=-1){
       $matchflag=1;
    }

    $occurence= () = $m =~ /$q/g;


    print("$matchflag\n");
    print($occurence);
}

#INPUT [uncomment & modify if required]
$n=<STDIN>;
$m=<STDIN>;
$p=<STDIN>;
$q=<STDIN>;


Solution();

Hello can someone tell me what's wrong with this code? It gives me the following output.

6
naman
nam
n
0
1

Clearly the 0 should be 1, because nam exists in naman string. and also 1 should be 2 as n occurs twice in the string.

What is wrong with this code?

Questioner
Naman Bansal
Viewed
74
Polar Bear 2020-02-01 08:51

OP probably meant the code be as follows

use strict;
use warnings;

my $n = input();
my $m = input();
my $p = input();
my $q = input();

Solution();

sub input{
    my $input = <STDIN>;

    chomp $input;

    return $input;
}

sub Solution{
    my $matchflag=0;
    my $occurence=0;

    #OUPTUT [uncomment & modify if required]
    my $ind=index($m,$p);


    if ($ind!=-1){
       $matchflag=1;
    }

    $occurence= () = $m =~ /$q/g;


    print("Match flag: $matchflag\n");
    print("Ocurance:   $occurence\n");
}

Output

6
naman
nam
n
Match flag: 1
Ocurance:   2