Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
This won't compile:
my $what = "fred|barney"; ... if ($_ =~ ($what){3}) { ... }
Dropping the () around $what will make it compile, but that really changes what the code is saying.
if ($_ =~ $what{3}) { ... }
is going to try to find the value in %what that is assosciated with the key '3' and use that as a regex. Unless you have some %what hash, this will be undef and will be intrepreted as
if ($_ =~ //) { ... }
which will match anything, including nothing. Essentially, that's just
if (1) { ... }
and you most likely do not want that.

This

my $what = "(fred|barney){3}"; ... if ($_ =~ $what) { ... }
probably does the closest to what you want (match three occurrences of 'fred' or 'barney' in any order. This works because =~ treats whatever it finds on the right hand side as a RE (regular expression).

You could get the same behavior from either of your examples by using the m// operator (the 'm' can be omited if you are using slashes as the delimiter).

if ($_ =~ /($what){3}/) { ... } .... if ($_ =~ /$what/) { ... }
If you do this, then you can eliminate the '$_ =~' as it is redundant:
if (/($what){3}/) { ... } ... if (/$what/) { ... }

Ivan Heffner
Sr. Software Engineer, DAS Lead
WhitePages.com, Inc.

In reply to Re: I'm reading a book! It's given me more questons! by Codon
in thread I'm reading a book! It's given me more questons! by Petras

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-24 03:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found