Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

good code 4

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
GB
hello,

not a problem but....

can anyone think of a good efficient way of doing the following. i have three variales that are passed to a function and may or may not be populated depending on some other function. I want to check these variables and if they're empty then just assign "N/A" to the variables. One obvious way would be to do three if statements but can anyone think of a better way of doing this...

jim
 
I usually accomplish that by using the ternary(?:) operator:

sub some_subroutine {
my $first_arg = shift;
my $second_arg = shift;
my $third_arg = shift;

$first_arg = defined($first_arg) ? $first_arg : "N/A";
$second_arg = defined($second_arg) ? $second_arg : "N/A";
$third_arg = defined($third_arg) ? $third_arg : "N/A";

or you might want to use

$first_arg = defined($first_arg) && $first_arg ne "" ? $first_arg : "N/A";

you get the idea...

HTH. Hardy Merrill
Mission Critical Linux, Inc.
 
If your list ever grows beyond three the following example could do the trick as long as your assigned variables contain an alphanumeric. Note $var5 is undefined while $var2 is null.

$var1 = "a";
$var2 = "";
$var3 = "b";
$var4 = "c";
@mylist = ($var1,$var2,$var3,$var4,$var5);
@mylist = &NA_missing(@mylist);

sub NA_missing{
map{if(/\w/){$_} else {"N/A"}}@_;
}
 
You could also use the ||= operator, which will assign a
new value only only if the old value is undef or zero, e.g.

my ($a, $b, $c) = map {$_ ||= "N/A"} @_;
 
mikevh

Now that is clever. I thought my if else was a bit clunky but didn't see a way past it. Learned something new, thanks!
 
I thought about it a little more, and you don't even need
"||=", just "||".

my ($a, $b, $c) = map {$_ || "N/A"} @_;

will do (almost) the same thing. The difference is that
the "||=" form always modifies the list that's input to
the map function, since "$_" is aliased to each consecutive
element. The second form doesn't necessarily, since it just
returns either the next list element or "N/A", whichever evaluates to "true" (not undef or zero) first. If you
assign to a different list on the left-hand side of the
map than you've got going in on the right, the original
list would be unchanged. But if "@_" held ($a, $b, $c) in
the first place (which I would assume it did), then it does change the original list, since you're assigning back into the same list.
back to the same list.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top