Chinaunix首页 | 论坛 | 博客
  • 博客访问: 829597
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-20 14:22:51

  1. my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
  2. my @skipper_with_name = ('Skipper', \@skipper);
  3. my @professor = qw(sunscreen water_bottle slide_rule batteries radio);
  4. my @professor_with_name = ('Professor', \@professor);
  5. my @gilligan = qw(red_shirt hat lucky_socks water_bottle);
  6. my @gilligan_with_name = ('Gilligan', \@gilligan);


  7. my @all_with_names = (
  8.   \@skipper_with_name,
  9.   \@professor_with_name,
  10.   \@gilligan_with_name,
  11. );

  12. print "${$all_with_names[1]}[0]\n";
  13. print "@{$all_with_names[1]}\n";
#Professor
#Professor ARRAY(0x8c351ec)


  1. my @array = (1, 2 );
  2.  my $ref = \@array;
  3.  $ref->[0]=100;
  4.  print @array;
  5. #1002

  1. $root = \@all_with_names;
  2. print "$root->[1]->[1]->[2]\n";
  3. print "$root->[1][1][2]\n";
  4. #slide_rule
  5. #slide_rule
Reference to hash
  1. my %gilligan_info = (
  2.   name => 'Gilligan',
  3.   hat => 'White',
  4.   shirt => 'Red',
  5.   position => 'First Mate',
  6. );
  7. my $hash_ref = \%gilligan_info;
  8. my @keys = keys % { $hash_ref };#get the keys.
  9. my $name = $ { $hash_ref } { 'name' }; #Gilligan

As with array references, we can use shortcuts to replace the complex curly-braced forms under some circumstances. For example, if the only thing inside the curly braces is a simple scalar variable (as shown in these examples so far), we can drop the curly braces:

  1. my $name = $$hash_ref{'name'};
  2. my @keys = keys %$hash_ref;

Like an array reference, when referring to a specific hash element, we can use an arrow form:

  1. my $name = $hash_ref->{'name'};

  1. my %gilligan_info = (
  2.   name => 'Gilligan',
  3.   hat => 'White',
  4.   shirt => 'Red',
  5.   position => 'First Mate',
  6. );
  7. my %skipper_info = (
  8.   name => 'Skipper',
  9.   hat => 'Black',
  10.   shirt => 'Blue',
  11.   position => 'Captain',
  12. );
  13. my @crew = (\%gilligan_info, \%skipper_info);



  14. Thus, $crew[0] is a hash reference to the information about Gilligan. We can get to Gilligan's name via any one of:

  15. ${ $crew[0] } { 'name' }
  16. my $ref = $crew[0]; $$ref{'name'}
  17. $crew[0]->{'name'}
  18. $crew[0]{'name



my $format = "%-15s %-7s %-7s %-15s\n"; printf $format, qw(Name Shirt Hat Position); for my $crewmember (@crew) { printf $format, $crewmember->{'name'}, $crewmember->{'shirt'}, $crewmember->{'hat'}, $crewmember->{'position'}; }
we can use hash slice to output
  1. for my $crewmember (@crew) {
  2.   printf $format, @$crewmember{qw(name shirt hat position)};
  3. }


阅读(518) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~