Forum Moderators: coopster & phranque

Message Too Old, No Replies

Is it OK to have a return in a loop?

         

csdude55

5:42 pm on Sep 21, 2021 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Before I rely on this, I want to make sure there's not a logical error with it.

I'm currently doing something like:

$filter = 0;

@arr = {
'one' => 1,
'two' => 2,
...
'ninety nine' => 99
};

foreach (keys @arr) {
if (/foo/) { $filter = $arr{$_}; last; }
}

if (!$filter && $something_else eq 'bar') { $filter = 100; }

if ($filter) { return $filter; }


Is there any reason why I shouldn't do it like this and eliminate $filter entirely?

foreach (keys @arr) {
if (/foo/) { return $arr{$_}; exit; }
}

if ($something_else eq 'bar') { return 100; }

Brett_Tabke

2:50 pm on Jun 5, 2022 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Nope, I do it a bunch of places here (even in the middle of the massive DecodePost routine (500 lines). Good info in this Perl Monks thread:


[perlmonks.org...]