Chovy’s Blog

Conditionally Checking Existence of a Value in Perl

Fri, June 1, 2007 — Category: Perl

Conditionally checking whether or not a variable exists in Perl.

There are many half-baked methods used for properly testing whether or not a variable is defined. Following are a few examples of some good and not-so good methods with explanations.


if (exists $opts{'primary'} || exists $opts{'secondary'}) {
    $some_value = $opts{'primary'} || $opts{'secondary'};
}

The above logic is clean and easy to follow at first glance, although it may not be the most efficient way of executing the appropriate decision making block.

Considering the above is equivalent to the following block, you may notice a somewhat redundant conditional checking that ensues:


if (exists $opts{'primary'} || exists $opts{'secondary'}) {
    if ( exists $opts{'primary'} ) {
        $some_value = $opts{'primary'};
    } else {
        $some_value = $opts{'secondary'};
    }
}

Another added benefit is that if your value is “0″ or empty, it may actually not get assigned if you use the simple one line conditional assignment:


$some_value = $opt{’primary’} || $opt{’secondary’};

The “primary option” would be skipped if it is equal to “0″…which is in-fact a completely valid value, and demonstrates the “falsey-ness” and “truthy-ness” of specific values…more on that later.

Thanks to “Ani-_” in #perl for setting me straight on conditional checking.

So, to some it all up in one bullet-proof conditional block for assignment we write the following, which will also turn out to run faster because there is only one conditional check:


if ( exists $opt{'primary'} ) {
    $some_value = $opt{'primary'};
elsif ( exists $opt{'secondary'} ) {
    $some_value = $opt{'secondary'};
} else {
    return false;
}

  • Post Conditionally Checking Existence of a Value in Perl to del.icio.us
  • Post Conditionally Checking Existence of a Value in Perl to digg
  • Post Conditionally Checking Existence of a Value in Perl to Furl
  • Add Conditionally Checking Existence of a Value in Perl to YahooMyWeb
  • Simpify!
  • Post Conditionally Checking Existence of a Value in Perl to shadows
  • Post Conditionally Checking Existence of a Value in Perl to Spurl
  • Post Conditionally Checking Existence of a Value in Perl to BuddyMarks
  • Submit Conditionally Checking Existence of a Value in Perl to Slashdot

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

 
Keyword Advertisers:
SEO Directory SEO Links Free Link Directory Shopping Submission Directory Gardening Tips Political Forum Search Engine Optimization Search Engine Marketing Audio Video Directory SEO Forum Web Development Blog Organic SEO Wiki Web Development Consulting

Learn more about purchasing keyword text link ads on this site.