http://www.perlmonks.org?node_id=1071577

jar00n has asked for the wisdom of the Perl Monks concerning the following question:

Working on a new script and was hoping to set a variable named $icase and attempt to match a string with this variable used as the operator. So if $icase is defined then it will be equal to 'i' otherwise it'll be undef. With that in mind, is that even logical/efficient/doable? Quick demo to show what I'm seeing:
#!/usr/bin/perl $icase = 'i'; $str = 'ASdf'; if ( 'asdf' =~ /$str/$icase ) { print "it works!\n" }
Which when ran produces this:
$ perl test.pl Scalar found where operator expected at test.pl line 6, near "/$str/$i +case" (Missing operator before $icase?) syntax error at test.pl line 6, near "/$str/$icase " Execution of test.pl aborted due to compilation errors.

Replies are listed 'Best First'.
Re: Can you use a scaler as an operator?
by hippo (Bishop) on Jan 22, 2014 at 10:04 UTC

    You would need to use Extended Patterns to accomplish this I think. eg.

    if ( 'asdf' =~ /(?$icase)$str/ ) { print "it works!\n" }

    See the perlre document for full details.

      Rather than using a defined vs undefined value for the op variable, here's an example of that approach using  'i' vs either  '#' or  '' (empty string).

      >perl -wMstrict -le "my $s = 'ASdf'; ;; for my $op ('i', '#', '') { printf qq{for op eq '$op': }; print 'asdf' =~ m{ (?$op) \Q$s\E }xms ? '' : 'NO ', 'match'; } " for op eq 'i': match for op eq '#': NO match for op eq '': NO match

      Update:  '-i' also works for turning off (or not turning on) case-insensitive matching.

      Very cool, I haven't stumbled across that syntax yet. Thanks
Re: Can you use a scaler as an operator?
by Eily (Monsignor) on Jan 22, 2014 at 10:06 UTC

    I'm afraid this won't work. You can either use an eval, use '/flags' mode, or use the (?adlupimsx-imsx) syntax. Personnaly, I don't like the second solution much, but the two others are mostly the same to me.

    Eventually, if it's just a case matter, and not any flag, you could also lc the input.