Phoenix
Phoenix

Reputation: 321

How to fetch values that are hard coded in a Perl subroutine?

I have a perl code like this:

use constant OPERATING_MODE_MAIN_ADMIN  => 'super_admin';
use constant OPERATING_MODE_ADMIN       => 'admin';
use constant OPERATING_MODE_USER        => 'user';
sub system_details
{
    return {
        operating_modes => {
            values => [OPERATING_MODE_MAIN_ADMIN, OPERATING_MODE_ADMIN, OPERATING_MODE_USER],
            help   => {
                'super_admin'  => 'The system displays the settings for super admin',
                'admin' => 'The system displays settings for normal admin',
                'user' => 'No settings are displayed. Only user level pages.'
            }
        },
        log_level => {
            values => [qw(FATAL ERROR WARN INFO DEBUG TRACE)],
            help   => "http://search.cpan.org/~mschilli/Log-Log4perl-1.49/lib/Log/Log4perl.pm#Log_Levels"
        },
    };
}

How will I access the "value" fields and "help" fields of each key from another subroutine? Suppose I want the values of operating_mode alone or log_level alone?

Upvotes: 0

Views: 65

Answers (2)

zdim
zdim

Reputation: 66899

The system_details() returns a hashref, which has two keys with values being hashrefs. So you can dereference the sub's return and assign into a hash, and then extract what you need

my %sys = %{ system_details() };

my @loglevel_vals = @{ $sys{log_level}->{values} };

my $help_msg = $sys{log_level}->{help};

The @loglevel_vals array contains FATAL, ERROR etc, while $help_msg has the message string.

This makes an extra copy of a hash while one can work with a reference, as in doimen's answer

my $sys = system_details();
my @loglevel_vals = @{ $sys->{log_level}->{values} };

But as the purpose is to interrogate the data in another sub it also makes sense to work with a local copy, what is generally safer (against accidentally changing data in the caller).

There are modules that help with deciphering complex data structures, by displaying them. This helps devising ways to work with data. Often quoted is Data::Dumper, which also does more than show data. Some of the others are meant to simply display the data. A couple of nice ones are Data::Dump and Data::Printer.

Upvotes: 2

dolmen
dolmen

Reputation: 8706

my $sys = system_details;
my $log_level = $sys->{'log_level'};

my @values = @{ $log_level->{'values'} };
my $help = $log_level->{'help'};

If you need to introspect the type of structure stored in help (for example help in operating_mode is a hash, but in log_level it is a string), use the ref builtin func.

Upvotes: 2

Related Questions