Chinaunix

标题: 分享一个遍历Hash的例子 [打印本页]

作者: Perl_Er    时间: 2014-11-26 15:04
标题: 分享一个遍历Hash的例子
  1. jzhu@jzhu-HP-Z400-Workstation:~/my-perl-scripts/chinaunix$ cat ../algorithm/traverse_hash.pl
  2. #!/usr/bin/perl
  3. use strict;
  4. use warnings;
  5. use v5.10;

  6. my %people = (
  7.     memowe => {
  8.         NAMES => {
  9.             memo => { AGE => 666 },
  10.             we   => { AGE => 667 },
  11.         },
  12.     },
  13.     bladepanthera => {
  14.         NAMES => {
  15.             blade    => { AGE => 42 },
  16.             panthera => { AGE => { Fuck => "you" } },
  17.         },
  18.     },
  19. );

  20. sub traverse (&$@) {
  21.     my ( $do_it, $data, @path ) = @_;

  22.     # iterate
  23.     foreach my $key ( sort keys %$data ) {

  24.         # handle sub-tree
  25.         if ( ref( $data->{$key} ) eq 'HASH' ) {
  26.             &traverse( $do_it, $data->{$key}, @path, $key );
  27.             next;
  28.         }

  29.         # handle leave
  30.         $do_it->( $data->{$key}, @path, $key );
  31.     }
  32. }

  33. traverse { say shift . " (@_)" } \%people;
  34. jzhu@jzhu-HP-Z400-Workstation:~/my-perl-scripts/chinaunix$ perl ../algorithm/traverse_hash.pl
  35. 42 (bladepanthera NAMES blade AGE)
  36. you (bladepanthera NAMES panthera AGE Fuck)
  37. 666 (memowe NAMES memo AGE)
  38. 667 (memowe NAMES we AGE)
复制代码

作者: huang6894    时间: 2014-11-26 15:32
先mark再看~
作者: inchonline    时间: 2014-11-26 22:06
22行的:sub traverse (&$@) {
函数里的&$@啥意思啊?
回复 1# Perl_Er


   
作者: Perl_Er    时间: 2014-11-27 09:20
回复 3# inchonline


    定义函数原型的, man perlsub找prototype




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2