Mega Code Archive

 
Categories / Perl / Data Type
 

Using ref inside a function

#!/usr/bin/perl use strict; use warnings; my @array1 = ( "This","is","the","first","array." ); my @array2 = ( "This","is","the","second","array." ); my %hash = ( Tarzan   => "A",              Superman => "B",              Batman   => "C", ); my $array3 = [ "A", [ "array", "in", "an", "array" ],                { "B" => "a",                  "C" => "in",                },                "D", "E" ];    printStructures( 5, \@array1, \%hash, \@array2, $array3); sub printStructures  {    my $indent = shift();        foreach my $element ( @_ ) {       unless ( ref( $element ) ) {          print( ' ' x $indent, $element, "\n" );       }       elsif ( ref( $element ) eq 'SCALAR' ) {          print( ' ' x $indent, $element, "\n" );       }       elsif ( ref( $element ) eq 'ARRAY' ) {          foreach ( 0 .. $#$element ) {             print( ' ' x $indent, "[ $_ ] " );             if ( ref( $element->[ $_ ] ) ) {                print( "\n" );                printStructures( $indent + 3, $element->[ $_ ] );             }             else {                print( "$element->[ $_ ]\n" );             }          }       }       elsif ( ref( $element ) eq 'HASH' ) {          foreach my $key ( keys( %$element ) ) {             print( ' ' x $indent, $key, ' => ' );             if ( ref ( $element->{ $key } ) ) {                print( "\n" );                printStructures( $indent + 3, $element->{ $key } );             }             else {                print( "$element->{ $key }\n" );             }          }       }       elsif ( ref( $element ) eq 'CODE' ) {          print( ' ' x $indent, "CODE\n" );       }       elsif ( ref( $element ) eq 'GLOB' ) {          print( ' ' x $indent, "GLOB\n" );       }              print( "\n" );    } }