Forum Moderators: coopster & phranque

Message Too Old, No Replies

defined() when function name is an array value

         

csdude55

6:58 pm on Sep 3, 2021 (gmt 0)

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



I have a list of conditions like this:

if ($_GET{'foo'} eq 'bar') { bar(); }
elsif ($_GET{'foo'} eq 'example') { example(); }
else { do_error_stuff; }


My real lists can have up to 20 conditions like that.

I'd like to shrink that down to something like:

if ($_GET{'foo'} && defined(&$_GET{'foo'})) { $GET{'foo'}(); }
else { do_error_stuff; }


What I found is that if I change the array value to a scalar then it works:

# This throws an error on the "defined" function
$_GET{'foo'} = 'bar';

if (
$_GET{'foo'} &&
defined(&$_GET{'foo'})
) {
&$_GET{'foo'};
exit;
}

else { print "no"; }

sub bar {
print "yes";
}


# But this works
$_GET{'foo'} = 'bar';
$foo = $_GET{'foo'};

if (
$foo &&
defined(&$foo)
) {
&$foo;
exit;
}

else { print "no"; }

sub bar {
print "yes";
}


Is there some other magical combination to use an array value here? I tried these variations, but none worked:

defined(&$_GET{'foo'})
defined &$_GET{'foo'}

defined($_GET{'foo'}())
defined $_GET{'foo'}()

Brett_Tabke

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

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



Nifty.

I've read quite a few places on the Perl lists that embedded if-then-elses are very memory intense. I've tested it quite a bit right here.

if ($foo) {
}
else {
return;
}

That is about 50% slower than something like
return if $foo eq "bar";

So I started using the 'post expression' form of if statements everywhere. I've even found this form to be much faster:

$target ="_top";
$target ="_blank" if $newwindow;


But being an old ML programmer - I am a subroutine junkie (and that is more expensive memory'wise than inline code).