Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

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 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.

Comment on Can you use a scaler as an operator?
Select or Download Code
Re: Can you use a scaler as an operator?
by hippo (Vicar) 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.

      Very cool, I haven't stumbled across that syntax yet. Thanks

      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.

Re: Can you use a scaler as an operator?
by Eily (Curate) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2015-07-04 23:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls