Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

You could join the array into a scalar with an unusual character as a separator, then use a match.

$foobar='D'; $sep = chr(1); @array = ('A','B','C','D'); if (($sep.join($sep,@array).$sep) =~ m/$sep$foobar$sep/) { print "Found a $foobar in \@array!"; }

The $sep on either side of the join() ensures that any potential match will begin and end with chr(1). You can pick other separator characters, as long as you can be sure they will not exist in your array (chr(1) is a pretty unlikely thing to find).

Of course, it would be better to use hash-keys if you can...

$foobar='D'; %hash = ( 'A' => undef, 'B' => undef, 'C' => undef, 'D' => undef ); print "Found a $foobar in \%hash" if exists $hash{$foobar};

If you're avoiding multiple loop passes for performance, then you could use a one-time loop to convert the array to a hash:

@array = ('A','B','C','D'); for (@array) { $hash{$_} = undef; } #now we have the same hash as in the previous example. #so, you can do this repeatedly with out a hit: $foo = 'D'; if (exists $hash{$foo}) { print "There was a $foo in the array\n"; }
radiantmatrix
require General::Disclaimer;
"Users are evil. All users are evil. Do not trust them. Perl specifically offers the -T switch because it knows users are evil." - japhy

In reply to Re: Compare all array values without a loop by radiantmatrix
in thread Compare all array values without a loop by Anonymous Monk

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 wandering the Monastery: (6)
As of 2024-03-19 05:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found