2011-04-21 122 views
1

有没有人有更好(更短)的方式在Perl中编写以下逻辑? 似乎升技繁琐,因为它是现在...我不想过度的变量传递给任何子程序的...如何将变量作为第一个参数传递给子例程?

#!perl 
use Data::Dumper; 

my $var = "ok"; 
my $bar = 1; 
my ($a, $b, $c) = (1,2,3); 

if ($var eq "ok") { 
    if (defined $bar) { 
     foo1($bar, $a); 
    } 
    else { 
     foo1($a); 
    } 
} 
elsif ($var eq "not_ok") { 
    if (defined $bar) { 
     foo2($bar, $a, $b); 
    } 
    else { 
     foo2($a, $b); 
    } 
} 
else { 
    if (defined $bar) { 
     foo3($bar, $a, $b, $c); 
    } 
    else { 
     foo3($a, $b, $c); 
    } 
} 

sub foo1 {print Dumper @_} 
sub foo2 {print Dumper @_} 
sub foo3 {print Dumper @_} 
+4

_ [丹楼](http://stackoverflow.com/users/718269/dan-f)_:请使用适合公共论坛的文字。我已经替换了这个词。 – 2011-04-21 04:53:56

回答

7
use 5.010; 
foo($bar //(), $a, $b, $c); 
+0

@Alan Haggai Alavi:谢谢 – ysth 2011-04-21 06:12:54

+0

_ [ysth](http://stackoverflow.com/users/17389/ysth)_:没问题。 :-) – 2011-04-21 06:55:14

2

你可以使用grep

foo(grep { defined } $where, $is, $pancakes, $house); 

这将过滤掉参数列表中的任何未定义的值。

+2

_ [太短](http://stackoverflow.com/users/479863/mu-is-too-short)_:感谢您使用不恰当的单词(问题中出现了这个单词)在你的答案中。 ** ++ ** – 2011-04-21 04:58:57

+1

@Alan:谢谢,我确实试图在有礼貌的公司观看我的语言。 OTOH,你现在距离你的Copy Editor徽章更近了一步,你对做一件好事感到很满意:) – 2011-04-21 05:24:03

+0

_ [mu太短](http://stackoverflow.com/users/479863/mu太短)_:很高兴知道这一点。是的,感觉很好。 :-) – 2011-04-21 05:44:21

1
if ($var eq "ok") { 
    foo1(defined $bar ? $bar :(), $a); 
} 
elsif ($var eq "not_ok") { 
    foo2(defined $bar ? $bar :(), $a, $b); 
} 
else { 
    foo3(defined $bar ? $bar :(), $a, $b, $c); 
} 
2

你还没说你的实际foo1/2/3潜艇做任何事情,所以这可能不适合你的情况,但我的第一反应是修改他们,使他们根本不理会第一个参数,如果它是undef。这样,您就可以直接拨打foo1($bar, $a, $b, $c);而不必担心是否定义了$bar

sub foo1 { 
    shift unless defined $_[0]; 
    # ...do other stuff now that any leading undef has been removed 
} 
0

你可以使用一个数组来建立你的参数列表:

my @args = ($a); 
unshift(@args, $bar) if defined $bar; 

if ($var eq "ok") { 
    foo1(@args); 
} 
elsif($var eq "not_ok") { 
    foo2(@args, $b); 
} 
else { 
    foo3(@args, $b, $c); 
} 
相关问题