2011-07-29 17 views
0
my %hash; 

my $input2 = "message"; 

#calling subroutine check_something 

$self->check_something (%hash, message => $input2); 

sub check_something { 

my $self   = shift; 
my %p    = @_; 
my $message   = $p{message}; 
my %hash   = @_; 

# do some action with the %hash and $input2; 

} 

私はハッシュ(%hash)を構築し、サブルーチンに渡したい別の変数を持っています。しかし、サブルーチンの中で私がやっているやり方は "my%hash = @_"も$ input2の値を取得します。これを避けるために私は何をすべきですか?ハッシュと変数をサブルーチンに渡します。

答えて

5

@_は配列なので、変数をそのように設定します。個々の部分に対処する場合は、$ _ [0]として扱うことができます。 REFによってハッシュを渡します

$self->check_something (\%hash, {message => $input2}); 
sub check_something { 
my ($self, $ref, $message) = @_; 

my %p = %{$ref}; 
# can reference the value of $input2 through $$message{'message'} or casting $message as a hash my %m = %{$message}; $m{'message'}; 
# do some action with the %hash and $input2; 

} 
+0

my%p =%{$ ref};私にハッシュ・ファインを取得します。 – user238021

+0

$ input2の値をサブルーチンの中に表示したいのですが、どうすればいいですか?私は$ message = $ _ [2]のような何かをするべきですか? – user238021

+0

私の12月に忘れました。それは私の($ self、$ ref、$ message、$ input)= @ _でなければなりません。 =>はカンマのように動作するので、文字列 "message"と$ input2があれば何でも構いません。 – scrappedcola

1

あなたは、まず、変数、ハッシュを渡すか、あなたはハッシュへの参照を渡します。

1

Perl flattens subroutine arguments - 単一のリストに - Perlはプロトタイプ化されていないすべてのサブルーチン呼び出しに対して自動的にhttp://en.wikipedia.org/wiki/Applyを実行します。したがって、$self->check_something (%hash, message => $input2);の場合、%hashは平坦化されます。

その場合:

%hash = (foo => 1, bar => 2); 

あなたのサブ呼び出しがある:だから

$self->check_something(foo => 1, bar => 2, message => $input2); 

、あなたは別のエンティティとしてあなたのハッシュを渡したい場合は、あなたが参照を渡す必要があります。

# Reference to hash: 
    $self->check_something(\%hash, message => $input2); 

    # To pass an anonymous copy:  
    $self->check_something({%hash}, message => $input2); 

    # To expand hash into an anonymous array: 
    $self->check_something([%hash], message => $input2); 

ほとんどの場合、私が示した最初の2つの例のいずれかを実行したいと思うでしょう。

リスト平滑化の利点は、プログラマチックに引数リストを作成するのが非常に簡単だということです。例:

my %args = (
    foo => 'default', 
    bar => 'default_bar', 
    baz => 23, 
); 

$args{foo} = 'purple' if $thingy eq 'purple people eater'; 

my %result = get_more_args(); 
@args{ keys %result } = values %result; 

my_amazing_sub_call(%args); 
関連する問題