Hi,
I got doubt in Pattern matching, could you tell me how the following differs in action ??
if ( $line1==/$line2/ )
if ( $line1=~/$line2/ )
if ( $line1=~m/$line2/)
What is the significance of '~' in matching.
Thanks in advance
CoolBhai
Hi,
I got doubt in Pattern matching, could you tell me how the following differs in action ??
if ( $line1==/$line2/ )
if ( $line1=~/$line2/ )
if ( $line1=~m/$line2/)
What is the significance of '~' in matching.
Thanks in advance
CoolBhai
The second and third lines you list are identical in function. The "m" (for match) is optional.
The =~ assigns the result of a regex subsitution to the variable. If you're doing a match, it doesn't do anything. If, instead of
$x =~ m/pattern/;
you were doing
$x =~ s/pattern/replacement/;
then you'd fill $x with the part(s) of itself matching the pattern replaced with the replacement.
Example:
$ perl -e '$x = "Fred"; print "$x\n"; $x =~ s/red/green/; print "$x\n";'
Fred
Fgreen
Thanks but then how to do a pattern matching ? what operator I should use ?? Below code doesnt work well for me.
#! C:\Perl\bin\perl
my $line1 = 'KUMAR';
my $line2 = 'RAM KUMAR';
if ($line1=/$line2/){
print "$line1 is present in $line2 \n";
}
Thanks ShawnMilo and pludi ,
The reason is
if ($line1=~ m/$line2/) tells whether $line2 is present in $line1 not viceversa.
Yes, besides having your syntax a bit off, your logic was not correct. The thing inside the regexp is the search pattern, not the string being searched.