abdel has asked for the wisdom of the Perl Monks concerning the following question:

hi there, I'm trying to understand the "if" statement used in a loop. what is the different between this two codes?

foreach my $hash ( keys %some ) { if ( $#{ $some{$hash} } >= 1 ) { print $#{ $some{$hash} } . "\n"; } }

the second code.

foreach my $hash ( keys %some ) { next if ( $#{ $some{$hash} } >= 1 ); print $#{ $some{$hash} } . "\n"; }

the first code I get printed the length of the array %some, if it contained 2 element or more. but the second code I get print, if it contain 3 element or more. why is those if-statement not the same output?

Replies are listed 'Best First'.
Re: if statement used in foreach-loop?
by BrowserUk (Patriarch) on Dec 10, 2010 at 03:58 UTC
    why is those if-statement not the same output?

    The first loop does the print if the value is >= 1.

    The second loop does the next if the value is >= 1.

    Or to put the latter a different way:

    The second loop doesn't do the print if the value is >=1.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: if statement used in foreach-loop?
by PeterPeiGuo (Hermit) on Dec 10, 2010 at 05:05 UTC

    The entire difference is centered on one thing - that "next" statement. "next" statement leads you to the next iteration (when the condition is satisfied), and skips the rest steps of this particular iteration. In some sense, your second piece of code is saying the opposite of your first piece (from the print statement's point of view).

    Peter (Guo) Pei

Re: if statement used in foreach-loop?
by roboticus (Chancellor) on Dec 10, 2010 at 10:20 UTC

    abdel:

    If you change the if to unless in your second bit of code, you'd get what you want. As the others indicated, you need to change your conditional in some way to take the same code path. Using unless inverts the condition, allowing you to use the same conditional. If you want to use if, rewriting the condition to ! ($#{ $some{$hash} } >= 1 would do it, as would $#{ $some{$hash} } < 1.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: if statement used in foreach-loop?
by JavaFan (Canon) on Dec 10, 2010 at 10:25 UTC
    but the second code I get print, if it contain 3 element or more.
    I do not believe that. Care to provide a short, runnable, example that shows this?