簡體   English   中英

將哈希和變量傳遞給子例程

[英]Pass hash and variable to subroutine

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),並有另一個要傳遞給子例程的變量。 但是,在子例程中,我執行“我的%hash = @_”的方式也獲得了$ input2的值。 我應該怎么做才能避免這種情況?

@_是一個數組,因此可以這樣設置變量。 如果要尋址單個片段,則可以尋址為$ _ [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;

}

您可以先傳遞變量,然后傳遞哈希,或者傳遞對哈希的引用。

Perl將子例程參數統一為一個列表-Perl自動將http://en.wikipedia.org/wiki/應用於所有非原型子例程調用。 因此,對於$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 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM