3

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?

1
  • See "Quote and Quote-like Operators" in "man perlop" (Perl Operators). Maybe also have a look at RTFM (which I remembered as fine, BTW).
    – U. Windl
    Commented Aug 23, 2023 at 13:26

2 Answers 2

6

It's a regular expression, , 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.

2
  • The actual value was 4 not k. I generalized it to k in an informed manner. Commented Aug 2, 2023 at 8:28
  • Wouldn't $array[k] substitute the value of $array, followed by the literal string "[k]", or would it raise a warning?
    – U. Windl
    Commented Aug 23, 2023 at 13:36
0

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.