Recursively printing data structures in Perl

前端 未结 8 1906
粉色の甜心
粉色の甜心 2021-01-13 05:32

I am currently learning Perl. I have Perl hash that contains references to hashes and arrays. The hashes and arrays may in turn contain references to other hashes/arrays.

8条回答
  •  借酒劲吻你
    2021-01-13 05:51

    You could have separated out the code blocks that dealt with arrays, and hashes.

    sub recurse{
      ...
      recurse_A(@_) if $ref eq 'ARRAY';
      recurse_H(@_) if $ref eq 'HASH';
      ...
    }
    
    sub recurse_A{ ... }
    sub recurse_H{ ... }
    

    I would recommend starting out your subroutines like this, unless you have a real good reason for doing otherwise.

    sub example{
      my( $one, $two, $three, $optional_four ) = @_;
    

    ( If you do it like this then Komodo, at least, will be able to figure out what the arguments are to your subroutine )

    There is rarely any reason to put a variable into a string containing only the variable.

    "$var" eq $var;
    

    The only time I can think I would ever do that is when I am using an object that has an overloaded "" function, and I want to get the string, without also getting the object.

    package My_Class;
    use overload
      '""' => 'Stringify',
    ;
    sub new{
      my( $class, $name ) = @_;
      my $self = bless { name => $name }, $class;
      return $self;
    }
    sub Stringify{
      my( $self ) = @_;
      return $self->{name};
    }
    

    my $object = My_Class->new;
    my $string = "$object";
    

提交回复
热议问题