Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Foreach loop

by marinersk (Priest)
on Sep 27, 2013 at 14:03 UTC ( #1055982=note: print w/replies, xml ) Need Help??

in reply to Foreach loop

Your need to work around whitespace is a Perl speciality. This looks like a C programmer's way to attempt the search; free your mind and embrace the Perl way:

Instead of index, use grep. The \s characters will accept any kind of whitespace, be it space character or tab, etc. This is the change I'd recommend:

OLD: $substr = " 1 "; NEW: $substr = '1'; my $regex = quotemeta $substr; OLD: if (index($key, $substr) != -1) {print "\nExist";} NEW: if (grep /\s$regex\s/, " $key ") {print "\nExist";}

Update: In order to ensure a leading or trailing '1' is captured, the grep was modified to include forced whitespace around $key.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1055982]
[Eily]: oh, boolean context uses the "" overload if no bool overload has been defined
[Eily]: (I wondered if overloading bool was actually necessary)
[Corion]: Yeah, you need bool to get a true value, and the rest to return the other value ;)
[choroba]: perl -wE '{package o; use Tie::Scalar; use parent -norequire => "Tie::StdScalar" ;sub FETCH { "x" x int rand 2}} tie my $x, "o" ; say $x for 1 .. 10'
[choroba]: for complete ness

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (9)
As of 2017-07-27 13:48 GMT
Find Nodes?
    Voting Booth?
    I came, I saw, I ...

    Results (414 votes). Check out past polls.