Perl: How do I declare empty array refs in a new hash? - arrays

I've got strict and warnings on, but it keeps complaining about the initialization of the following line:
$hash{$key} = ($row, [], [], [], '');
It warns for that single line:
"Useless use of private variable in void context"
"Useless use of anonymous list ([]) in void context" (3 times)
I am filling the data in later, but I want indexes 1, 2, 3 to be array references, and index 4 to be a string. I am accessing and filling the data like so:
$hash{$key}->[1]->[3] = 'Data';
$hash{$key}->[4] = $hash{$key}->[4] . 'More Data';
Obviously, I'm doing something wrong, but I'm not exactly sure how to make it right. (Also, I'm aware that that last line is redundant, could that also be summed up in a nicer way?)

Elements of a hash can only be scalars, so you have to change your assignment to use the anonymous array constructor instead of parens:
$hash{$key} = [$row, [], [], [], ''];
See perldsc for more information.
The line:
$hash{$key}->[4] = $hash{$key}->[4] . 'More Data';
could be written:
$hash{$key}->[4] .= 'More Data';
And finally, unless you like them, the -> characters are implicit between subscript delimiters, so $hash{$key}->[1]->[3] means the same thing as $hash{$key}[1][3]

I'm not quite sure what you are trying to do, but if you want to assign an array to a scalar value, you need to use brackets to create an anonymous array:
$hash{$key} = [$row, [], [], [], ''];
In your case, what you are attempting to do is interpreted as follows:
$row, [], [], [];
$hash{$key} = '';
Because you cannot assign a list of values to a scalar (single value variable). You can, like we did above, however, assign a reference to an anonymous array containing a list of values to a scalar.

You almost got it.
Remember that every hash and array value must be a scalar, so if you want a hash of arrays, you have to assign an array reference to your hash key. So:
$hash{$key} = [ $row, [], [], [], '' ];
is what you want.

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

Powershell create array of arrays

I'm trying to push data to a REST api using powershell.
http://influxdb.com/docs/v0.8/api/reading_and_writing_data.html
The server expects data like so:
[
{
"name" : "hd_used",
"columns" : ["value", "host", "mount"],
"points" : [
[23.2, "serverA", "mnt"]
]
}
]
However, I"m only able to make a json object that looks like this (notice the extra quotes):
[
{
"name" : "hd_used",
"columns" : ["value", "host", "mount"],
"points" : [
"[23.2, "serverA", "mnt"]"
]
}
]
How can I construct the data into an array of arrays without wrapping the nested array in quotes?
This works, but it isn't a nested array
$influxdata = [ordered]#{}
$influxdata.name = $hd_used
$influxdata.columns = #("value", "host", "mount")
$influxdata.points = #()
$influxdata.points += #("23.2", "serverA", "mnt")
$influxdatajson = $influxdata | ConvertTo-Json -Depth 2
This works but the inner array is actually a string.
$influxdata = [ordered]#{}
$influxdata.name = $hd_used
$influxdata.columns = #("value", "host", "mount")
$influxdata.points = #()
$influxdata.points += #('["23.2", "serverA", "mnt"]')
$influxdatajson = $influxdata | ConvertTo-Json -Depth 2
With $PSVersion.$PSVersion equal to 3.0 and your exact input I get the following when I print the $influxdatajson variable:
{
"name": "hd_used",
"columns": [
"value",
"host",
"mount"
],
"points": [
"23.2",
"serverA",
"mnt"
]
}
Which clearly isn't what you want but isn't what you said you got either.
The reason that that is the output we get is because your attempt to add the array to the existing array didn't work the way you expect because of powershell's annoying tendency to unroll arrays (I think).
If you work around that oddity by using this syntax instead:
$influxdata.points += ,#("23.2", "serverA", "mnt")
(the leading , forces an array context so that outer array gets unrolled instead of the array you are trying to add)
then I get the following output from $influxdatajson:
{
"name": "hd_used",
"columns": [
"value",
"host",
"mount"
],
"points": [
[
"23.2",
"serverA",
"mnt"
]
]
}
To complement Etan Reisner's helpful answer (whose of use unary , to create a nested array solves the problem):
PowerShell's hashtable literals are quite flexible with respect to incorporating variable references, expression, and commands, which makes for a more readable solution:
,, [ordered] #{
name = 'hd_used'
columns = 'value', 'host', 'mount'
points = , (23.2, 'serverA', 'mnt')
} | ConvertTo-Json -Depth 3
This yields:
[
{
"name": "hd_used",
"columns": [
"value",
"host",
"mount"
],
"points": [
[
23.2,
"serverA",
"mnt"
]
]
}
]
Note how the array-construction operator (,) is applied twice at the beginning of the pipeline (before [ordered]):
first to turn the ordered hashtable into a (single-item) array,
and the 2nd time to wrap that array in an outer array.
Sending the result through the pipeline makes PowerShell unwrap any collection, i.e., enumerate the collection items and send them one by one, which in this case strips away the outer array, leaving ConvertTo-Json to process the inner array, as desired.
Note that passing an array adds a level to the hierarchy, which is why the -Depth value was increased to 3 above.
Caveat: Any property whose hierarchy level is deeper than -Depth is stringified (evaluated as if placed inside "$(...)"), which in the case of an array would simply join the array elements with a space; e.g., array 23.2, 'serverA', 'mnt' would turn to a single string with literal contents 23.2 serverA mnt.
Note how the arrays above do not use syntax #(...), because it is generally not necessary to construct arrays and is actually less efficient: simply ,-enumerate the elements, and, if necessary, enclose in (...) for precedence (although #() is syntactically convenient for creating an empty array).
+ with an array as the LHS doesn't so much unwrap (unroll) its RHS, but concatenates arrays, or, to put it differently, allows you to append multiple individual items; e.g.:
$a = 1, 2
$a += 3, 4 # add elements 3 and 4 to array 1, 2 to form array 1, 2, 3, 4
Note that the use of += actually creates a new array behind the scenes, given that arrays aren't resizable.
Just to add my two pence worth. Its is worth noting that everytime you touch an array and you know is a single item array, you must use the appropriate comma syntax. This is not well highlighted in articles I found on the subject.
Take this example case I wrote for a Pester test case:
A lesson about single item arrays, every time you touch a single item array, you must use the comma op. It is not a case of set it and forget it:
Mock get-AnswerAdvancedFn -ModuleName Elizium.Loopz {
$pairs = #(, #('Author', 'Douglas Madcap Adams'));
$first = $pairs[0];
Write-Host "=== SINGLE-ITEM: pairs.count: $($pairs.Count), first.count: $($first.Count)"
([PSCustomObject]#{ Pairs = $pairs })
}
The above won't work, because of the fault assigning $pairs to Pairs even though we've used the correct syntax setting $pairs to #(, #('Author', 'Douglas Madcap Adams'))
The following fixes this issue; everytime you touch the single item array, you must use the comma syntax, otherwise you give PowerShell another chance to flatten your array:
Mock get-AnswerAdvancedFn -ModuleName Elizium.Loopz {
$pairs = #(, #('Author', 'Douglas Madcap Adams'));
$first = $pairs[0];
Write-Host "=== SINGLE-ITEM: pairs.count: $($pairs.Count), first.count: $($first.Count)"
([PSCustomObject]#{ Pairs = , $pairs })
}
My test code ended up being this:
Mock get-AnswerAdvancedFn -ModuleName Elizium.Loopz {
([PSCustomObject]#{ Pairs = , #(, #('Author', 'Douglas Madcap Adams')) })
}
Note, we had to use the comma op twice and both of those are necessary

Cannot assign to "" in "self" - Working with Tuples in Swift

I have to classes: FirstViewController and PlanGenerator.
PlanGenerator has a method called getPlanForIndex (day:Int) -> ([PlanElement], [PlanElement])?. It is returning two different Arrays, both containing Object of Plan Element.
getPlanForIndex (day:Int) -> ([PlanElement], [PlanElement])? {
// Do some work and fill arrays
return (firstArray, secondArray)
}
In the FirstViewController I've created two Properties:
let plan:[PlanElement] = [PlanElement]()
let planGen:PlanGenerator = PlanGenerator()
FirstViewControllerhas a method called:
func prepareView () {
plan = planGen.getPlanForIndex(dayIndex)
}
But when I want to call this, I get the error message:
Cannot assign to 'plan' in 'self'
First, your plan member is a constant (declared with let), and you're assigning to it outside of init. If you want to assign to it after initialization, it needs to be declared with var.
Also, your getPlanForIndex returns a tuple, and you're assigning it to a member of singular (not tuple) type. If you want to assign one part of a tuple only, do it like this:
(plan, _) = planGen.getPlanForIndex(dayIndex)
That assigns a tuple to a tuple, satisfying the compiler, but discards the second element.
If you instead want plan to be a tuple, you'll have to declare and initialize it as such. Looks from the comments like you figured out a way to do that, but here's a way with minimal typing (in either sense of the word):
var plan: ([PlanElement], [PlanElement]) = ([], [])
(Once you've declared the type of array, [] is understood to be an empty array of that type. Just var plan = ([], []) leaves the type ambiguous.)

About accessing the Array of Arrays

I once read the following example about "array of arrays". AOA is a two dimensional array
The following code segment is claimed to print the whole thing with refs
for $aref ( #AoA ) {
print "\t [ #$aref ],\n";
}
And the following code segment is claimed to print the whole thing with indices
for $i ( 0 .. $#AoA ) {
print "\t [ #{$AoA[$i]} ],\n";
}
What's the $aref stand for here? How to understand the definition of #$aref and #{$AoA[$i]}? Thanks.
$aref stands for "array reference", i.e. a reference for an array.
my $my_aref = \#somearray;
You can make an array from an array reference with the following syntax:
#{$my_aref}
#{$my_aref} is #somearray. (It's not a copy, it really is the same array.)
In second example, $AoA[$i] is an array reference, and you dereference it with the same syntax: #{$AoA[$i]}.
See perlreftut for more explanations and examples.
An "array of arrays" isn't actually an array of arrays. It's more an array of array references. Each element in the base array is a reference to another array. Thus, when you want to cycle through the elements in the base array, you get back array references. These are what get assigned to $aref in the first loop. They are then de-referenced by pre-pending with the # symbol, so #$aref is the array referenced by the $aref array reference.
Same sort of thing works for the second loop. $AoA[$i] is the $i-th element of the #AoA array, which is an array reference. De-referencing it by pre-pending it with the # symbol (and adding {} for clarity, and possibly for precedence) means #{$AoA[$i]} is the array referenced by the $AoA[$i] array reference.
Perl doesn't have multidimensional arrays. One places arrays into other arrays to achieve the same result.
Well, almost. Arrays (and hashes) values are scalars, so one cannot place an array into another array. What one does instead of place a reference to an array instead.
In other words, "array of arrays" is short for "array of references to arrays". Each value of the #AoA is a reference to another array, given the "illusion" of a two-dimensional array.
The reference come from the use [ ] or equivalent. [ ] creates an anonymous array, then creates a reference to that array, then returns the reference. That's where the reference comes from.
Common ways of building an AoA:
my #AoA = (
[ 'a', 'b', 'c' ],
[ 'd', 'e', 'f' ],
);
my #AoA;
push #AoA, [ 'a', 'b', 'c' ];
push #AoA, [ 'd', 'e', 'f' ];
my #AoA;
$AoA[$y][$x] = $n;
Keep in mind that
$AoA[$y][$x] = $n;
is short for
$AoA[$y]->[$x] = $n;
and it's equivalent to the following thanks to autovivification:
( $AoA[$y] //= [] )->[$x] = $n;
The whole mystery with multi-dimension structures in perl is quite easy to understand once you realize that there are only three types of variables to deal with. Scalars, arrays and hashes.
A scalar is a single value, it can contain just about anything, but
only one at the time.
An array contains a number of scalar values, ordered by a fixed
numerical index.
A hash contains scalar values, indexed by keys made of strings.
And all arrays, hashes or scalars act this way. Multi-dimension arrays are no different from single dimension.
This is also expressed very succinctly in perldata:
All data in Perl is a scalar, an array of scalars, or a hash of
scalars. A scalar may contain one single value in any of three
different flavors: a number, a string, or a reference. In general,
conversion from one form to another is transparent. Although a scalar
may not directly hold multiple values, it may contain a reference to
an array or hash which in turn contains multiple values.
For example:
my #array = (1, 2, 3);
Here, $array[0] contains 1, $array[1] contains 2, etc. Just like you would expect.
my #aoa = ( [ 1, 2, 3 ], [ 'a', 'b', 'c' ] );
Here, $array[0] contains an array reference. If you print it out, it will say something like ARRAY(0x398a84). Don't worry! That's still a scalar value. How do we know this? Because arrays can only contain scalar values.
When we do something like
for $aref ( #AoA ) {
print $aref; # prints ARRAY(0x398a84) or similar
}
It's no different from doing
for $number ( #array ) {
print $number;
}
$aref and $number are scalar values. So far, so good. Take a moment and lock this knowledge down: Arrays can only contain scalar values.
Now, the next part is simply knowing how to deal with references. This is documented in perlref and perlreftut.
A reference is a scalar value. It's an address to a location in memory. This location contains some data. In order to access the actual data, we need to dereference the reference.
As a simple example:
my #data = (1, 2, 3);
my $aref = \#data; # The backslash in front of the sigil creates a reference
print $aref; # print something like ARRAY(0xa4b6a4)
print #$aref; # prints 123
Adding a sigil in front of the reference tells perl to dereference the scalar value into the type of data the sigil represents. In this case, an array. If you choose the wrong sigil for the type of reference, perl will give an error such as:
Not a HASH reference
In the example above, we have a reference to a specific, named location. Both #$aref and #data access the same values. If we change a value in one, both are affected, because the address to the memory location is identical. Let's try it:
my #data = (1, 2, 3);
my $aref = \#data;
$$aref[1] = 'a'; # dereference to a scalar value by $ sigil
# $aref->[1] = 'a' # does the same thing, a different way
print #data; # prints 1a3
print #$aref; # prints 1a3
We can also have anonymous data. If we were only interested in building an array of arrays, we'd have no interest in the #data, and could skip it by doing this:
my $aref = [ 1, 2, 3 ];
The brackets around the list of numbers create an anonymous array. $aref still contains the same type of data: A reference. But in this case, $aref is the only way we have of accessing the data contained at the memory location. Now, let's build some more scalar values like this:
my $aref1 = [ 1, 2, 3 ];
my $aref2 = [ 'a', 'b', 'c' ];
my $aref3 = [ 'x', 'y', 'z' ];
We now have three scalar variables that contain references to anonymous arrays. What if we put these in an array?
my #aoa = ($aref1, $aref2, $aref3);
If we'd want to access $aref1, we could do print #$aref1, but we could also do
print #{$aoa[0]};
In this case, we need to use the extended form of dereferencing: #{ ... }. Because perl does not like ambiguity, it requires us to distinguish between #{$aoa[0]} (take the reference in $aoa[0] and dereference as an array) and #{$aoa}[0] (take the reference in $aoa and dereference as an array, and take that arrays first value).
Above, we could have used #{$aref}, as it is identical to #$aref.
So, if we are only interested in building an array of arrays, we are not really interested in the $aref1 scalars either. So let's cut them out of the process:
my #aoa = ( [ 1, 2, 3 ], [ 'a', 'b', 'c' ], [ 'x', 'y', 'z' ]);
Tada! That's an array of arrays.
Now, we can backtrack. To access the values inside this array, we can do
for my $scalar ( #aoa ) {
print #$scalar; # prints 123abcxyz
}
This time, I used a different variable name, just to make a point. This loop takes each value from #aoa -- which still is only a scalar value -- dereferences it as an array, and prints it.
Or we can access #aoa via its indexes
for my $i ( 0 .. $#aoa ) {
print #{$aoa[$i]};
}
And that's all there is to it!

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