I am looking at a Perl script to figure what it does.
I came across this
if (/:$array[k]/)
What does /:$something/
do in Perl?
I am looking at a Perl script to figure what it does.
I came across this
if (/:$array[k]/)
What does /:$something/
do in Perl?
It's a regular expression, regex, matching against $_
.
Specifically the $
is not treated as a regex special character here, but starts expression evaluation instead (the expression is $array[k]
.
So it matches :
followed by whatever is in $array[k]
. $array[k]
looks wrong though. It should probably be $array[$k]
.
Example:
#!/bin/perl
my @array=qw(foo bar baz);
$_ = 'XXX:barXXX';
my $k = 1;
if (/:$array[$k]/) { # :$array[$k] is ":bar"
print "Match\n"; # prints Match because :bar is found in $_
}
Note: If the elements in array
are not supposed to be interpreted as regex
patterns as they would in your original example, you'll need to quote the interpolation of $array[$k]
with \Q
...\E
:
if (/:\Q$array[$k]\E/)
\E
can be left out in the above example since we want everything after \Q
to be matching literally.
$array[k]
substitute the value of $array
, followed by the literal string "[k]", or would it raise a warning?
Perl's regular expressions are a double-quoted context. This means it will interpolate the same sequences any other double-quoted context before it constructs the pattern. Whatever is in $array[$k]
is now part of the pattern, and any special meta-characters are still special.