Nicely display a reference to something (hash, array or scalar) in Perl

Below is a little function to display a reference to mainly a hash, array or scalar in Perl:

Code:

use strict;
use warnings;

our $indentationString = "    ";

sub recursive_ref_string
{
        my $depth = shift;
        my $ref = shift;
        my $string = '';

        if ( ref( $ref ) eq 'HASH' )
        {
                $string .= "{\n";
                $depth++;
                for my $key ( sort keys %{ $ref } )
                {
                        $string .= sprintf( "%s%s => ", $indentationString x $depth, $key );
                        $string .= &recursive_ref_string( $depth, $ref->{ $key } );
                        $string .= ",\n";
                }
                $depth--;
                $string .= sprintf( "%s}", $indentationString x $depth );
        }
        elsif ( ref( $ref ) eq 'ARRAY' )
        {
                $string .= "[\n";
                $depth++;
                for my $item ( @{ $ref } )
                {
                        $string .= sprintf( "%s'%s',\n", $indentationString x $depth, $item );
                }
                $depth--;
                $string .= sprintf( "%s]", $indentationString x $depth );
        }
        elsif ( ref( $ref ) eq 'SCALAR' )
        {
                $string .= "'${ $ref }'";
        }
        elsif ( defined( $ref ) )
        {
                $string .= "'$ref'";
        }
        else
        {
                $string .= 'undef';
        }
        return $string;
}

sub ref_string
{
        my $ref = shift;
        return &recursive_ref_string( 0, $ref );
}


my $scalar = 'Hello World';
my @array = qw( a b c d );
my %hash = (
        un => 1,
        deux => \$scalar,
        trois => \@array,
);

printf( "Scalar reference: %s\n\n", &ref_string( \$scalar ) );
printf( "Array reference: %s\n\n", &ref_string( \@array ) );
printf( "Hash reference: %s\n\n", &ref_string( \%hash ) );

Result:

Scalar reference: 'Hello World'

Array reference: [
    'a',
    'b',
    'c',
    'd',
]

Hash reference: {
    deux => 'Hello World',
    trois => [
        'a',
        'b',
        'c',
        'd',
    ],
    un => '1',
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s