$stuff = "d:/learning/perl/tmp.txt";
open STUFF, $stuff or die "Cannot open $stuff for read :$!";
while (<STUFF>) {
my($line) = $_; # Good practice to always strip the trailing
chomp($line);
my @values = split(' ', $line);
foreach my $val (@values) {
if ($val == 1){
print "1 found";
}
elsif ($val =~ /hello/){
print "hello found";
}
elsif ($val =~ /"/*"/){ # I don't know how to handle here.
print "/* found";
}
print "\n";
}
}
My tmp.txt
:
/* CheerStone ColdStunner
1 Cheer Rock
hello Boo Pedigree
How do I handle the /*
character sequence in my code?
The *
is a special character. So, you have to escape it:
m{/\*}
As Adam Bellaire has suggested, here is a brief explanation:
Picket-fences are best avoided. For that, sometimes, delimiters other than /
have to be used. m
should precede the first delimiter when using such delimiters. If any of the brackets are used as the first delimiter, the corresponding closing bracket has to be used as the end delimiter.
There are various ways to un-meta regex metacharacters. In your case, you need to handle the character that is the default delimiter as well as a meta-character.
In the case of a delimiter character that you want to be a literal character, you can escape that character with \, although you can get leaning toothpick syndrome:
m/\/usr\/local\/perls/;
You can change the delimiter:
m(/usr/local/perl);
You can escape meta-characters in the same way:
m(/usr/local/perl\*);
If you want a section of your pattern to be only literal characters, you can use \Q
to automatically escape them for you:
m(\Q/usr/local/perl*);
If you want a smaller section of your pattern to be only literal characters, you can use \Q
then turn it off with \E
:
m(/usr/local/perl\Q*+?\E/);
The \Q
is really the same thing as quotemeta. Putting your pattern into a variable then interpolating it in the match operator also solves the delimiter problem:
my $pattern = quotemeta( '/usr/local/perl*+?/' );
m/$pattern/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With