2011-07-29 5 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]; 참조로 해시 전달 :

+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); 

는 대부분의 경우에, 당신은 아마 내가 보여 처음 두 예제 중 하나를 수행 할 것입니다.

목록 평탄화 행동의 이점은 프로그래밍 방식 인수 목록을 구축하는 것은 매우 쉽습니다입니다. 예 :

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); 
관련 문제