Using ref inside a function : ref « Data Type « Perl






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" );
   }
}

   
    
    
    
  








Related examples in the same category

1.Return Values from the ref Function
2.Using ref function on a subroutine reference
3.Using ref function to check the parameter type
4.Using ref function to get the type of the reference
5.The return values of the ref function: ref( \\@array )
6.The return values of the ref function: function
7.The return values of the ref function: ref( \*hash )
8.The return values of the ref function: 10
9.The return values of the ref function: array