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

Re: looking for simple way to check scalar against array

by tcf03 (Deacon)
on May 19, 2005 at 15:01 UTC ( [id://458646]=note: print w/replies, xml ) Need Help??


in reply to looking for simple way to check scalar against array

Like this?
#!/usr/bin/perl -w use strict; my $i = 4; my @nums = ( 1 .. 9 ); push (@nums, -12); for (@nums) { print if /$i/; }

or
#!/usr/bin/perl -w use strict; my $i = 4; for ( 1 .. 9, -12 ) { print if /$i/; }
UPDATE
What blazar ikegami and dug said.
My example was to show you what you might not want to do, but may or may not work anyway.
Ted
--
"That which we persist in doing becomes easier, not that the task itself has become easier, but that our ability to perform it has improved."
  --Ralph Waldo Emerson

Replies are listed 'Best First'.
Re^2: looking for simple way to check scalar against array
by ikegami (Patriarch) on May 19, 2005 at 15:11 UTC

    Why use a regexp? It's inefficient, and that particular regexp will fail if 1) $i contains special characters, and 2) if $i is part of another number (e.g. when $i=1 and list=(2..10), your regexp will match).

    print if /^\Q$i\E$/ would fix the problem.
    print if $_ eq $i is equivalent, but much more efficient.
    print if $_ == $i would be even more efficient given that we're dealing with numbers here.

Re^2: looking for simple way to check scalar against array
by dug (Chaplain) on May 19, 2005 at 15:12 UTC
    If the list contains anything with a 4 in it you will get a match, which I don't think is what the OP wants. If you are going to use the regex approach it should probably be anchored on both ends: /^$i$/.

    update: Not that you really needed a third person to remind you [grin].

    -- Douglas
Re^2: looking for simple way to check scalar against array
by blazar (Canon) on May 19, 2005 at 15:09 UTC
    Gawd, believe me: I'm very keen on regexen myself, but I wouldn't use one where what you really want is an equality operator! And in that case it should be
    /^$i$/ if you qw/really wanted to do it like that/;

    Update: As duly pointed out by ikegami, to be really more precise, one should use /^\Q$i\E$/, which may seem nitpicking wrt this particular example, but which can be also absolutely necessary in other situations... (well, not that you would use this actual regex, but maybe a somewhat similar one.)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://458646]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-19 17:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found