Perl - How do I update (and access) an array stored in array stored in a hash?

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-07 04:18:26

问题


Perhaps I have made this more complicated than I need it to be but I am currently trying to store an array that contains, among other things, an array inside a hash in Perl.

i.e. hash -> array -> array

use strict;

my %DEVICE_INFORMATION = {}; #global hash

sub someFunction() {
    my $key = 'name';
    my @storage = ();

    #assume file was properly opened here for the foreach-loop
    foreach my $line (<DATA>) {
        if(conditional) {
            my @ports = ();

            $storage[0] = 'banana';
            $storage[1] = \@ports;
            $storage[2] = '0';

            $DEVICE_INFORMATION{$key} = \@storage;      
        }

        elsif(conditional) {
            push @{$DEVICE_INFORMATION{$key}[1]}, 5;
        }
    }#end foreach
} #end someFunction

This is a simplified version of the code I am writing. I have a subroutine that I call in the main. It parses a very specifically designed file. That file guarantees that the if statement fires before subsequent elsif statement.

I think the push call in the elsif statement is not working properly - i.e. 5 is not being stored in the @ports array that should exist in the @storage array that should be returned when I hash the key into DEVICE_INFORMATION.

In the main I try and print out each element of the @storage array to check that things are running smoothly.

#main execution
&someFunction();

print $DEVICE_INFORMATION{'name'}[0];
print $DEVICE_INFORMATION{'name'}[1];
print $DEVICE_INFORMATION{'name'}[2];

The output for this ends up being... banana ARRAY(blahblah) 0

If I change the print statement for the middle call to:

print @{$DEVICE_INFORMATION{'name'}[1]};

Or to:

print @{$DEVICE_INFORMATION{'name'}[1]}[0];

The output changes to banana [blankspace] 0

Please advise on how I can properly update the @ports array while it is stored inside the @storage array that has been hash'd into DEVICE_INFORMATION and then how I can access the elements of @ports. Many thanks!

P.S. I apologize for the length of this post. It is my first question on stackoverflow.


回答1:


I was going to tell you that Data::Dumper can help you sort out Perl data structures, but Data::Dumper can also tell you about your first problem:

Here's what happens when you sign open-curly + close-curly ( '{}' ) to a hash:

use Data::Dumper ();

my %DEVICE_INFORMATION = {}; #global hash
print Dumper->Dump( [ \%DEVICE_INFORMATION ], [ '*DEVICE_INFORMATION ' ] );

Here's the output:

%DEVICE_INFORMATION  = (
                         'HASH(0x3edd2c)' => undef
                       );

What you did is you assigned the stringified hash reference as a key to the list element that comes after it. implied

my %DEVICE_INFORMATION = {} => ();

So Perl assigned it a value of undef.

When you assign to a hash, you assign a list. A literal empty hash is not a list, it's a hash reference. What you wanted to do for an empty hash--and what is totally unnecessary--is this:

my %DEVICE_INFORMATION = ();

And that's unnecessary because it is exactly the same thing as:

my %DEVICE_INFORMATION;

You're declaring a hash, and that statement fully identifies it as a hash. And Perl is not going to guess what you want in it, so it's an empty hash from the get-go.

Finally, my advice on using Data::Dumper. If you started your hash off right, and did the following:

my %DEVICE_INFORMATION; # = {}; #global hash    
my @ports = ( 1, 2, 3 );

# notice that I just skipped the interim structure of @storage
# and assigned it as a literal 
# * Perl has one of the best literal data structure languages out there.
$DEVICE_INFORMATION{name} = [ 'banana', \@ports, '0' ];
print Data::Dumper->Dump( 
      [ \%DEVICE_INFORMATION ]
    , [ '*DEVICE_INFORMATION' ] 
    );

What you see is:

%DEVICE_INFORMATION  = (
                         'name' => [
                                     'banana',
                                     [
                                       1,
                                       2,
                                       3
                                     ],
                                     '0'
                                   ]
                       );

So, you can better see how it's all getting stored, and what levels you have to deference and how to get the information you want out of it.

By the way, Data::Dumper delivers 100% runnable Perl code, and shows you how you can specify the same structure as a literal. One caveat, you would have to declare the variable first, using strict (which you should always use anyway).




回答2:


You update @ports properly.
Your print statement accesses $storage[1] (reference to @ports) in wrong way.
You may use syntax you have used in push.

print $DEVICE_INFORMATION{'name'}[0], ";",
      join( ':', @{$DEVICE_INFORMATION{'name'}[1]}), ";",
      $DEVICE_INFORMATION{'name'}[2], "\n";
print "Number of ports: ", scalar(@{$DEVICE_INFORMATION{'name'}[1]})),"\n";
print "First port: ", $DEVICE_INFORMATION{'name'}[1][0]//'', "\n";
# X//'' -> X or '' if X is undef


来源:https://stackoverflow.com/questions/32771192/perl-how-do-i-update-and-access-an-array-stored-in-array-stored-in-a-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!