2

次のよりエレガントな書き方は何ですか?

sub depend {
    my($x,$y) = @_;
    die "only one allowed" if( defined($x) && defined($y) );
    die "one must be defined" unless ( defined($x) || defined($y) );
    if( defined($x) ) {
         $y = somefunc($x);
    } else {
         $x = somefunc($y);
    }
    return($x,$y);
 }

この関数は、引数を 1 つだけ取得する必要があります。両方が定義されている場合 = エラー、定義されていない場合 = エラー。そして、未定義の引数は、定義されたものに基づいて計算されます。

4

4 に答える 4

1

サブルーチンを2 つの引数を取るように定義するかもしれませんが、それらをキーと値のペアとして扱います。コメントの幅/高さの例を使用するには:

sub depend {
    my $key = shift;
    my $value = shift;
    die "One parameter only" if @_;
    return ($value, calc_height($value)) if $key eq "width";
    return (calc_width($value), $value) if $key eq "height";
    die "Must specify either height or width, not $key";
}

my ($w1, $h1) = depend( width => 5 );
my ($w2, $h2) = depend( height => 10 );
my ($w3, $h3) = depend();  # ERROR Must specify either height or width
my ($w4, $h4) = depend( other=>3 );  # ERROR Must specify either height or width, not other
my ($w5, $h5) = depend( foo => bar, 7); # ERROR, One parameter only
于 2013-05-20T22:48:55.940 に答える
-1

使用xorは直感的ではない可能性があり、以下のソリューションはより多くの入力引数に簡単に拡張できます。

 sub depend {
    my($x,$y) = @_;

    die "There should be only one!" if (grep defined, $x,$y) != 1;

    if( defined($x) ) {
         $y = somefunc($x);
    }
    else {
         $x = somefunc($y);
    }
    return($x,$y);
}
于 2013-05-20T19:00:42.300 に答える