Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Can you use a scaler as an operator?

by jar00n (Novice)
on Jan 22, 2014 at 09:48 UTC ( #1071577=perlquestion: print w/ replies, xml ) Need Help??
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 Scalar found where operator expected at line 6, near "/$str/$i +case" (Missing operator before $icase?) syntax error at line 6, near "/$str/$icase " Execution of aborted due to compilation errors.

Replies are listed 'Best First'.
Re: Can you use a scaler as an operator?
by hippo (Prior) 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 (Priest) 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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1071577]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2016-08-28 13:09 GMT
Find Nodes?
    Voting Booth?
    The best thing I ever won in a lottery was:

    Results (393 votes). Check out past polls.