Perl: Adding more elements to array created from hash - arrays

I have a perl script where we are converting Hash into array-
my %info = (
'name' => $1,
'ip' => $2,
'parent' => '',
'isLocal' => 0,
'clip' => 0,
);
my #siteinfos = ();
push( #siteinfos, \%info );
Now I am able to accesss the array by-
foreach my $site(#siteinfos) {
if ( $site->{'name'} eq $sitename) {
.....
}
First I am not sure how this conversion actually works.Secondly,Now I want to add more elements to this array in (key,pair) format.How can I do so?

First, there is no conversion.
my #siteinfos = ();
defines an array #siteinfos and sets to the empty list. Of course, you could have achieved the same result by using just
my #siteinfos;
Next, the statement
push( #siteinfos, \%info );
pushes a reference to the hash %info to #siteinfos as the sole element of that array.
Next, the loop
foreach my $sinfo (#siteinfos) { # assuming original is a typo
ends up aliasing $sinfo to that sole hash reference in #siteinfos. In the body of the loop, you access an element of the original hash via the reference you pushed to #siteinfos.
Now, things would have been different if you had done:
push #siteinfos, %info;
That would have set #siteinfos to a list like the following (the order is non-deterministic):
$VAR1 = [
'ip',
undef,
'clip',
0,
'isLocal',
0,
'name',
undef,
'parent',
''
];
The undef are there because the match variables were empty when I ran the script. Now, if you want to push another key-value pair to this array, that's trivial:
push #siteinfos, $key, $value;
But of course, by assigning the hash to an array, you are losing the ability to simply look up values by key. In addition, you can keep pushing duplicate keys to an array, but if you assign it back to another hash:
my %otherinfo = #siteinfos;
then only the last version of an even-indexed element (key) and its corresponding odd-indexed element (value) will survive.

You are not converting anything. You are making a new array named #siteinfos.
my #siteinfos = ();
Then you add one entry, which is a reference to the hash %info.
push( #siteinfos, \%info );
The array now holds a reference to %info. That's $siteinfo[0].
In your loop you iterate all the elements in #siteinfos. The hashref now goes into $sinfo.
If you want to add more keys and values to that hashref, just put them in.
foreach my $sinfo (#siteinfos) {
if ( $sinfo->{'name'} eq $sitename) {
$sinfo->{foo} = "bar"; # as simple as this
}
}

Related

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

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.
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).
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

Pushing an array reference repeatedly: the pushed references end up all equal

I want to create a 2d array(#combinations) that holds all combinations of another array (#indices).
I'm using push to append a reference to another array(#temp2). When I print my 2d array (using Dumper) it is not as I expect: the print statement inside the loop shows that every pushed reference is to a non-empty list, but eventually all my references point to an empty list. Why?
use Math::Combinatorics;
use Data::Dumper;
my (#combinations, #temp2);
my #indices = (0, 2, 4);
my $count = 1;
my $counter = #indices;
while ($counter>= $count) {
my $c = Math::Combinatorics->new(
count => $count,
data => \#indices,
);
$count++;
while (#temp2 = $c->next_combination) {
print "#temp2 \n";
push #combinations, \#temp2;
}
}
print Dumper(\#combinations);
Because you declare #temp2 at the top level, the reference \#temp2 will always point to the same data. Because you exit the loop as soon as #temp2 is empty, all the references in #combinations will point to this same empty array.
The remedy is easy: declare the #temp2 to be local to the while loop, by writing
while (my #temp2 = $c->next_combination) {
This will create a new variable #temp2, with its own reference, each time the loop is repeated.

Loop 1st element of 2d List

I have a list like this
[[hash,hash,hash],useless,useless,useless]
I want to take the first element of hashes and loop through it - i try this:
my #list = get_list_somehow();
print Dumper($list[0][0]); print Dumper($list[0][1]);print Dumper($list[0][2]);
and i am able to access the elements fine manually, but when i try this
my #list = get_list_somehow()[0];
print Dumper($list[0]); print Dumper($list[1]);print Dumper($list[2]);
foreach(#list){
do_something_with($_);
}
only $list[0] returns a value (the first hash, everything else is undefined)
You are taking a subscript [0] of the return value of get_list_somehow() (although technically, you need parentheses there). What you need to do is to dereference the first element in that list. So:
my #list = get_list_somehow();
my $first = $list[0]; # take first element
my #newlist = #$first; # dereference array ref
Of course, this is cumbersome and verbose, and if you just want to print the array with Data::Dumper you can just do:
print Dumper $list[0];
Or if you just want the first array, you can do it in one step. Although this looks complicated and messy:
my #list = #{ (get_list_somehow())[0] };
The #{ ... } will expand an array reference inside it, which is what hopefully is returned from your subscript of the list from get_list_somehow().
I'm taking that your sample data looks like this:
my #data = [
{
one => 1,
two => 2,
three => 3,
},
"value",
"value",
"value",
];
That is, the first element of #data, $data[0] is your hash. Is that correct?
Your hash is a hash reference. That is the $data[0] points to the memory location where that hash is stored.
To get the hash itself, it must be dereferenced:
my %hash = %{ $data[0] }; # Dereference the hash in $data[0]
for my $key ( keys %hash ) {
say qq( \$hash{$key} = "$hash{$key}".);
}
I could have done the dereferencing in one step...
for my $key ( keys #{ $data[0] } ) {
say qq(\$data[0]->{$key} = ") . $data[0]->{$key} . qq(".);
}
Take a look at the Perl Reference Tutorial for information on how to work with references.
I'm guessing a bit on your data structure here:
my $list = [
[ { a => 1,
b => 2,
c => 3, },
{ d => 4, }
{ e => 5, }
], undef, undef, undef,
];
Then we get the 0th (first) element of the top-level array reference, which is another array reference, and then the 0th (first) element of THAT array reference, which is the first hash reference:
my $hr = $list->[0][0];
And iterate over the hash keys. That could also be written as one step: keys %{ $list->[0][0] }. It's a bit easier to see what's going on when broken out into two steps.
for my $key (keys %$hr) {
printf "%s => %s\n", $key, $hr->{$key};
}
Which outputs:
c => 3
a => 1
b => 2

How to pass value of a hash of arrays into a subroutine?

I have a hash of arrays. I'm trying to do the following: as I'm looping through the keys of the hash, I would like to pass the value of the hash (in this case the array) into a subroutine.
Once I'm in the subroutine, I'd like to do a bunch of calculations with the array including take the average of the numeric values in the array. Lastly return a value based on the calculations.
Here's a minimal representation of what I have:
#!/usr/bin/perl
use warnings; use strict;
use List::Util qw(sum);
%data_set = (
'node1' => ['1', '4', '5', '2'],
'node2' => ['3', '2', '4', '12'],
'node3' => ['5', '2', '3', '6'],
);
foreach my $key ( keys %data_set ) {
foreach ( #{$data_set{$key}} ) {
my #array = split; # it's not letting me
calculate(\#array); ### I'm getting the error here!!
}
}
sub calculate{
my #array = #{$_};
my $average = mean(\#array);
# do some more calculations
return; # return something
}
# sum returns the summation of all elements in the array
# dividing by #_ (which in scalar content gives the # of elements) returns
# the average
sub mean{
return sum(#_)/#_;
}
Quick clarification: On the first iteration node1, I'd like to pass the array '1', '4', '5', '2' into the subroutine.
I think for my purposes this might be a bit more efficient than passing a reference to the hash of arrays into each subroutine. What do you guys think? In any case, can you guys help me figure this out? Any suggestions are appreciated. thanks
I think you are a bit confused about when you need to reference and dereference variables as well as what you are passing, where.
Lets look at this closer,
foreach my $key ( keys %data_set ) {
foreach ( #{$data_set{$key}} ) {
my #array = split; # it's not letting me
calculate(\#array); ### I'm getting the error here!!
}
}
You loop over the hash to get the keys, but then you use them to access the values to dereference the arrays and split each array into a single element array (of a string). Then you pass a reference to that 1-element array to calculate. Basically, you are doing too much work if the only thing that you want to do is pass each value of the hash (the arrays) into the calculate subroutine. Try something like this:
foreach my $key (keys %data_set){
calculate($data_set{$key}); # This is already a reference to an array
}
Additionally, in calculate you need to change my #array = #{$_}; to either my #array = #{$_[0]}; or my #array = #{(shift)};
Your mean subroutine should look something like this:
sub mean{
my #array = #{(shift)};
return sum(#array)/scalar(#array);
}

Filling hash of multi-dimensional arrays in perl

Given three scalars, what is the perl syntax to fill a hash in which one of the scalars is the key, another determines which of two arrays is filled, and the third is appended to one of the arrays? For example:
my $weekday = "Monday";
my $kind = "Good";
my $event = "Birthday";
and given only the scalars and not their particular values, obtained inside a loop, I want a hash like:
my %Weekdays = {
'Monday' => [
["Birthday", "Holiday"], # The Good array
["Exam", "Workday"] # The Bad array
]
'Saturday' => [
["RoadTrip", "Concert", "Movie"],
["Yardwork", "VisitMIL"]
]
}
I know how to append a value to an array in a hash, such as if the key is a single array:
push( #{ $Weekdays{$weekday} }, $event);
Used in a loop, that could give me:
%Weekdays = {
'Monday' => [
'Birthday',
'Holiday',
'Exam',
'Workday'
]
}
I suppose the hash key is the particular weekday, and the value should be a two dimensional array. I don't know the perl syntax to, say, push Birthday into the hash as element [0][0] of the weekday array, and the next time through the loop, push another event in as [0][1] or [1][0]. Similarly, I don't know the syntax to access same.
Using your variables, I'd write it like this:
push #{ $Weekdays{ $weekday }[ $kind eq 'Good' ? 0 : 1 ] }, $event;
However, I'd probably just make the Good/Bad specifiers keys as well. And given my druthers:
use autobox::Core;
( $Weekdays{ $weekday }{ $kind } ||= [] )->push( $event );
Note that the way I've written it here, neither expression cares whether or not an array exists before we start.
Is there some reason that
push #{ $Weekdays{Monday}[0] }, "whatever";
isn’t working for you?

Resources