CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Getting first of 3 variable values

 



bulrush
User

Jul 9, 2015, 11:14 AM

Post #1 of 4 (1841 views)
Getting first of 3 variable values Can't Post

I have a question about this line:


Code
$val = $var1 || $var2 || $var3 or die "Could not find value!";


Does this mean if $var1 is set, put it into $val? If not $val1, then get $val2 if defined. If not $val2 then get $val3. Is it equivalent to:


Code
if ($var1) 
{$val=$var1;
}
elsif ($var2)
{$val=$var2;
}
elsif ($var3)
{$val=$var3;
}

-----


FishMonger
Veteran / Moderator

Jul 9, 2015, 12:04 PM

Post #2 of 4 (1835 views)
Re: [bulrush] Getting first of 3 variable values [In reply to] Can't Post

Questions like this are best answered and understood by simply running a test yourself to compare the results.

That being said, I will answer the question. Yes, they are basically equivalent, but there are better/cleaner ways to do that. One being the first() function from the List::Util module. Another would be to refactor the code so that it's using an array or hash instead of a group of sequentially numbered scalars.


bulrush
User

Jul 9, 2015, 12:10 PM

Post #3 of 4 (1833 views)
Re: [FishMonger] Getting first of 3 variable values [In reply to] Can't Post

Ok, doing it this way actually ignores undef values and blank values! Very handy in many situations. So it grabs the first defined, non-blank value out of all variables listed.
-----


(This post was edited by bulrush on Aug 4, 2015, 11:30 AM)


Laurent_R
Veteran / Moderator

Jul 9, 2015, 2:36 PM

Post #4 of 4 (1827 views)
Re: [bulrush] Getting first of 3 variable values [In reply to] Can't Post


In Reply To
Does this mean if $var1 is set, put it into $val? If not $val1, then get $val2 if defined. If not $val2 then get $val3.


More or less the idea, but not exactly.

This means: if $var1 is set and true, then assign $val to it. In other words, if $var1 is set to 0 or "", it is not true and you'll need to check $val2, and so on if $val2 is set but false.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives