in reply to Search string within an predefined array

Maybe you're looking for last?

But it won't work that way, because if you break out of the loop in the else branch, you're just checking the first item. Maybe just set a variable to a true value in the if branch, and do the print after the loop.

That said, this kind of problem is usually solved with hashes instead:

my @defstream = ("HF","HFB","MB","BF"); my %d; @d{@defstream} = (1) x @defstream: if ($d{$dfs}) { ... } else { ... }

Replies are listed 'Best First'.
Re^2: Search string within an predefined array
by ack (Deacon) on Jan 16, 2009 at 16:27 UTC

    I have often had a similar challenge and have almost always used the method that moritz suggests. I find it's simple, clean and provides a strategy that works for arbitrarily complex, nested if() statements.

    One thing I've been trying to do, however, is to actually put the code that needs to be executed (in your case when the if()'s first test is TRUE) in the body of the block that the if() goes to. That way, at least IMHO, it is even more obivious (e.g., 'reader friendly').

    However, I have also found that such a strategy only works if (1) the block of code to execute is short enought that readers don't loose track of which enclosing if() clause it belongs to and (2) there aren't a lot of if() clauses or nestings.

    So, by and large, I stick with the method that moritz recommended.

    ack Albuquerque, NM
Re^2: Search string within an predefined array
by hbm (Hermit) on Jan 16, 2009 at 17:02 UTC
    Yes to the hash! But I would change the if to this:
    if (exists $d{$dfs}) {

    It's a moot point in this example since all the values are 1; but relevant if your values could be zero...

Re^2: Search string within an predefined array
by dilip_val (Acolyte) on Jan 16, 2009 at 17:41 UTC
    Hi Moritz, Can you help me understand what the lines

    @d{@defstream} = (1) x @defstream;
    and
    if ($d{$dfs})
    mean.
      I'm not moritz, but I'll give it a shot...
      @d{@defstream} = (1) x @defstream;
      This is a way to initialize the %d hash variable. Each element of the @defstream array is used as a hash key, and all values of the hash will equal 1. @d{@defstream} is a hash slice (see Subscripts). Also see Multiplicative Operators for an explanation of "x". It is equivalent to the more verbose:
      foreach my $dfs (@defstream) { $d{$dfs} = 1; }
      if ($d{$dfs})
      The "if" tests if the expression in the parentheses, which is a hash subscript, is true. I think moritz probably meant to use:
      if ($d{$stream}) {
      This will test whether the %d hash contains a key whose name is given by the value of the $stream variable. As hbm points out, it may be more appropriate to use exists.