开发者

dereferencing hash from params

开发者 https://www.devze.com 2023-01-02 17:26 出处:网络
This code works: my $href = shift @_;# get reference to hash my %h = %{$href};# dereference hash This one does not:

This code works:

  my $href = shift @_;    # get reference to hash
  my %h = %{$href};       # dereference hash

This one does not:

  my %h = %{shift @_};

As well as this one:

  my %h = ${$_[0]}

Why?

=============================

One more time to be precisly:

 1 #!/usr/bin/perl -w
  2 use strict;
  3 use warnings;
  4 
  5 my %h;
  6 sub a {
  7     
  8     # that works - result 1
  9     my $href = $_[0] || shift;
 10     %h = %{$href};
 11     
 12     # that does not work - result 0
 13     # my %h = %{$_[0]};
 14     
 15     # as well as that one - result 0
 16     # my %h = %{shift @_};
 17     $h{1}=2;
 18 }
 19 
 20 a(\%h);
 21 print scalar (keys %h) . "\n";

In other words line 16 - it does开发者_如何学JAVAn't.


This will work.

  my %h = %{shift @_};

This won't.

  my %h = ${$_[0]} # not ${$_[0]}

That sigil is supposed to be %

  my %h = %{$_[0]}

also, use warnings;, and use strict;


HINT: The reason your above example doesn't work, is only one example doesn't declare a lexical variable %h = %{$href}; is not my %h = %{$href};

0

精彩评论

暂无评论...
验证码 换一张
取 消