I have an array like so:
#switch_ports = ()
and then want to add 50 instances of this hash, to the switch_ports array.
%port = (data1 => 0, data2 => 0, changed => 0)
However, if I push my hash to the array:
push(#switch_ports, %port)
and I do print #switch_ports, I just see:
data10data20changed0
so it just seems to be adding them to the array, (joining them)
and if I try and loop the array and print the keys, it also fails.
Can you store a hash in an array?
Can you have an array of hashes?
I'm trying to get this:
switchports
0
data1
data2
changed
1
data1
....
thus:
foreach $port (#switchport) {
print $port['data1']
}
would return all of the data1 for all of the hashes in the array.
In Perl, array and hash members must be a single value. Before Perl 5.0, there was no (easy) way to do what you want.
However, in Perl 5 you can now use a reference to your hash. A reference is simply the memory location where the item is being stored. To get a reference, you put a backslash in front of the variable:
use feature qw(say);
my $foo = "bar";
say $foo; #prints "bar"
say \$foo; #prints SCALAR(0x7fad01029070) or something like that
Thus:
my #switch_ports = ();
my %port = ( data1 => 0, data2 => 0, changed => 0 );
my $port_ref = \%port;
push( #switch_ports, $port_ref );
And, you don't have to create $port_ref:
my #switch_ports = ();
my %port = ( data1 => 0, data2 => 0, changed => 0 );
push( #switch_ports, \%port );
To get the actual value of the reference, simply put the symbol back on front:
#Remember: This is a REFERENCE to the hash and not the hash itself
$port_ref = $switch_ports[0];
%port = %{$port_ref}; #Dereferences the reference $port_ref;
print "$port{data1} $port{data2} $port{changed}\n";
Another shortcut:
%port = %{$port[0]}; #Dereference in a single step
print "$port{data1} $port{data2} $port{changed}\n";
Or, even shorter, dereferencing as you go along:
print ${$port[0]}{data1} . " " . ${$port[0]}{data2} . " " . ${$port[0]}{changed} . "\n";
And a little syntactic sweetener. It means the same, but is easier to read:
print $port[0]->{data1} . " " . $port[0]->{data2} . " " . $port[0]->{changed} . "\n";
Take a look at Perldoc's perlreftut and perlref. The first one is a tutorial.
When you try:
%port = (data1 => 0, data2 => 0, changed => 0);
push #switch_ports, %port;
What really happens is:
push #switch_ports, "data1", 0, "data2", 0, "changed", 0;
Because arrays and hashes will automatically break into their elements when used in list context.
When you want to create 50 instances of a hash, it is not a good idea to use a reference to an existing hash as others have suggested, as that will only create 50 different references to the same hash. Which will crash and burn for obvious reasons.
What you need is something like:
push #array, { data1 => 0, data2 => 0, changed => 0 } for 1 .. 50;
Which will add 50 unique anonymous hashes to the array. The braces denotes construction of an anonymous hash, and returns a scalar reference to it.
ETA: Your example of how to access this data is wrong.
foreach $port (#switchport) {
print $port['data1']; # will use #port, not $port
}
Using a subscript on a scalar variable will attempt to access an array in that namespace, not a scalar. In perl, it is valid to have two separate variables $port and #port. Brackets are used for arrays, not hashes. When using references, you also need to use the arrow operator: $port->{data1}. Hence:
for my $port (#switchport) {
print $port->{data1};
}
You can store a reference to a hash in an array:
push #switchport, \%port; # stores a reference to your existing hash
or
push #switchport, { %port }; # clones the hash so it can be updated separately
Then iterate with, say,
foreach my $port (#switchport) {
print $port->{'data1'}; # or $$port{'data1'}
}
See man perlref.
To simplify for those who use this question to find a general approach - as in the Heading Question. Mysql theme:
my #my_hashes = ();
my #$rows = ... # Initialize. Mysql SELECT query results, for example.
if( #$rows ) {
foreach $row ( #$rows ) { # Every row to hash, every hash to an array.
push #my_hashes, {
id => $row->{ id },
name => $row->{ name },
value => $row->{ value },
};
}
}
To loop and print out:
for my $i ( 0 .. $#my_hashes ) {
print "$my_hashes[$i]{ id }\n ";
print "$my_hashes[$i]{ name }\n ";
print "$my_hashes[$i]{ value }\n ";
}
or
for my $i ( 0 .. $#my_hashes ) {
for my $type ( keys %{ $my_hashes[$i] } ) {
print "$type=$my_hashes[$i]{$type} ";
}
}
Related
So if I have some data object and I want to access whats inside the element of that object
Whats the difference between
$Data{isEnabled})
$Data->{isEnabled}
my data is basically like this
for my $characterData (#{$AllCharacters->{'characters'}}) {
$Data{isEnabled})
$Data->{isEnabled}
and i want to access certain elements of my characterData but I'm not sure when to use
$Data{isEnabled})
vs
$Data->{isEnabled}
Like for example why does the first print work but the second fails?
use strict;
use warnings;
my %info = (NAME => "John", HOST => "Local", PORT => 80);
print $info{PORT};
print $info->{PORT};
The first expression accesses a key within a hash:
my %data = (is_enabled => 1);
print $data{is_enabled}), "\n";
In the second expression, data is not a hash, but a *hash reference. It would typically be declared as:
my $data = { is_enabled => 1 };
Since this is a reference, we need to use the dereferencing operator (->) to access the hash content:
print $data->{is_enabled}, "\n";
If you are iterating through an array of hashes, as your code seems to show, then each element is a hash reference. You need to use the second syntax:
my #all_data = ( { is_enabled => 1 }, { is_enabled => 0 } );
for my $data (#all_data) {
print $data->{is_enabled}, "\n";
}
You can read more about references in the perlref documentation page.
$Data->{isEnabled}
is equivalent to
${ $Data }{isEnabled}
I prefer the "arrow" notation, but it serves my explanation better to compare
$Data{isEnabled}
with
${ $Data }{isEnabled}
In the first case ($Data{isEnabled}), we are accessing an element of a hash %Data.
In the second case, we also appear to have a hash lookup, but we have a block ({ $Data }) where a name would normally be expected. It is indeed a hash lookup, but instead of accessing a named hash, we are accessing a referenced hash. The block (or the expression to the left of the ->) is expected to return a reference to the hash the program should access.
A reference is a means of referencing a variable through it's location in memory rather than by its name. Consider the following example:
my $ref;
if (condition()) {
$ref = \%hash1;
} else {
$ref = \%hash2;
}
say $ref->{id};
This will print $hash1{id} or $hash2{id} based on whether condition() returns a true value or not.
I know this topic has been covered but other posts usually has static hashes and arrays and the don't show how to load the hashes and arrays.
I am trying to process a music library. I have a hash with album name and an array of hashes that contain track no, song title and artist. This is loaded from an XML file generated by iTunes.
the pared down code follows:
use strict;
use warnings;
use utf8;
use feature 'unicode_strings';
use feature qw( say );
use XML::LibXML qw( );
use URI::Escape;
my $source = "Library.xml";
binmode STDOUT, ":utf8";
# load the xml doc
my $doc = XML::LibXML->load_xml( location => $source )
or warn $! ? "Error loading XML file: $source $!"
: "Exit status $?";
my %hCompilations;
my %track;
# extract xml fields
my #album_nodes = $doc->findnodes('/plist/dict/dict/dict');
for my $album_idx (0..$#album_nodes) {
my $album_node = $album_nodes[$album_idx];
my $trackName = $album_node->findvalue('key[text()="Name"]/following-sibling::*[position()=1]');
my $artist = $album_node->findvalue('key[text()="Artist"]/following-sibling::*[position()=1]');
my $album = $album_node->findvalue('key[text()="Album"]/following-sibling::*[position()=1]');
my $compilation = $album_node->exists('key[text()="Compilation"]');
# I only want compilations
if( ! $compilation ) { next; }
%track = (
trackName => $trackName,
trackArtist => $artist,
);
push #{$hCompilations{$album}} , %track;
}
#loop through each album access the album name field and get what should be the array of tracks
foreach my $albumName ( sort keys %hCompilations ) {
print "$albumName\n";
my #trackRecs = #{$hCompilations{$albumName}};
# how do I loop through the trackrecs?
}
This line isn't doing what you think it is:
push #{$hCompilations{$album}} , %track;
This will unwrap your hash into a list of key/value pairs and will push each of those individually onto your array. What you want is to push a reference to your hash onto the array.
You could do that by creating a new copy of the hash:
push #{$hCompilations{$album}} , { %track };
But that takes an unnecessary copy of the hash - which will have an effect on your program's performance. A better idea is to move the declaration of that variable (my %track) inside the loop (so you get a new variable each time round the loop) and then just push a reference to the hash onto your array.
push #{$hCompilations{$album}} , \%track;
You already have the code to get the array of tracks, so iterating across that array is simple.
my #trackRecs = #{$hCompilations{$albumName}};
foreach my $track (#trackRecs) {
print "$track->{trackName}/$track->{trackArtist}\n";
}
Note that you don't need the intermediate array:
foreach my $track (#{$hCompilations{$albumName}}) {
print "$track->{trackName}/$track->{trackArtist}\n";
}
first of all you want to push the hash as a single element, so instead of
push #{$hCompilations{$album}} , %track;
use
push #{$hCompilations{$album}} , {%track};
in the loop you can access the tracks with:
foreach my $albumName ( sort keys %hCompilations ) {
print "$albumName\n";
my #trackRecs = #{$hCompilations{$albumName}};
# how do I loop through the trackrecs?
foreach my $track (#trackRecs) {
print $track->{trackName} . "/" . $track->{trackArtist} . "\n";
}
}
I have this code segment to put together a hash of parameters which I will pass to a function. The hash value containing the IP address is supposed to be an array reference, but the function I'm passing my parameters to thinks it's a scalar reference.
My code is:
my $paramList = "ldap_ip_addresses=['192.168.1.100']|ldap_port=389|ldap_protocol=ldap";
my #paramTuples = split(/\|/, $paramList);
my %nasProps;
foreach my $paramTuple (#paramTuples) {
my($key, $val) = split(/=/, $paramTuple, 2);
# SetProperties can also take hashes or arrays
my $eval_val = eval $val;
if (ref($eval_val) =~ /ARRAY/) {
$val = \$eval_val;
}
$nasProps{$key} = $val;
}
From the debugger, my parameter hash looks like this:
DB<18> x \%nasProps
0 HASH(0x303f8f0)
'ldap_authentication_type' => 'anonymous'
'ldap_ip_addresses' => REF(0x303fa70)
-> ARRAY(0x8284eb8)
0 '192.168.1.100'
'ldap_port' => 389
'ldap_protocol' => 'ldap'
It looks like a reference to an array so I'm not sure where I'm going wrong.
Since $eval_val is already a reference to an array, there is no need to make a reference to the reference. Change:
$val = \$eval_val;
to:
$val = $eval_val;
You are unnecessarily taking the reference to a reference with
$val = \$eval_val;
You have established on the previous line that $eval_val is a reference to an array, so you can use it as it is without taking a reference to it again.
In addition, you should ignore the result of ref $eval_val except to check that it is true — i.e. $eval_val is a reference of some sort.
Your code should look more like this. You need to fall back to the original $val value only if eval returns undef, usually meaning that the string wasn't compilable code.
Note also that you should reserve capital letters for global Perl variables, such as package names. Lexical variable identifiers should contain only lower-case letters, decimal digits and underscores.
use strict;
use warnings;
my $param_list = "ldap_ip_addresses=['192.168.1.100']|ldap_port=389|ldap_protocol=ldap";
my #param_tuples = split /\|/, $param_list;
my %nas_props;
for my $param_tuple (#param_tuples) {
my ($key, $val) = split /=/, $param_tuple, 2;
$nas_props{$key} = eval($val) // $val;
}
use Data::Dump;
dd \%nas_props;
output
{
ldap_ip_addresses => ["192.168.1.100"],
ldap_port => 389,
ldap_protocol => "ldap",
}
Here is a short alternative in functional style:
my %nasProps =
map /\[/ ? eval : $_,
split /[|=]/, $paramList;
However, it only works if you can guarantee that = is not included in any parameter values.
I have been trying examples for hours but I can't seem to grasp how to do what I want to do.
I want to return a hash from a subroutine, and I figured a reference was the best option. Here's where it gets a bit tricky. I want to reference a hash like $hash{$x}. I am still a noob at perl :/
1.First question, the examples I use seem to show it is ok to use $hashTable{$login}, should I be using %hashTable{$login} or does it not matter? Below is the code:
sub authUser {
$LocalPath = "/root/UserData";
open(DATAFILE, "< $LocalPath");
while( $linebuf = <DATAFILE> ) {
chomp($linebuf);
my #arr = split(/:/, $linebuf);
my $login = $arr[1]; # arr[1] contains the user login names
my $hashTable{ $login } = "$arr[0]"; #$arr[0] is account number
}
close DATAFILE;
return \$hashTable{ $login };
}
I then want to test this data to see if a login is present, here is my test method
# test login Dr. Brule which is present in UserData
my $test = "Dr. Brule";
my $authHash = &authUser();
if ( $authHash{ $test } ) {
print "Match for user $test";
}
else {
print "No Match for user $test";
}
2.Should my $authHash be really $authHash{ $something }, I am so confused on this
Edit: After some reading tips, still attempting but no dice, any help would be greatly appreciated
Edit 2: Can anyone modify my code so that I can understand the answers better? I'm sorry I can't seem to get this to work at all, I have been trying for hours and I really want to know the correct way to do this, I can post my various tries but I feel that will be a waste of real estate.
First off, as mpapec mentioned in comments, use strict; use warnings;. That will catch most common mistakes, including flagging most of the problems you're asking about here (and usually providing hints about what you should do instead).
Now to answer questions 1 and 2:
%hash is the hash as a whole. The complete data structure.
$hash{key} is a single element within the hash.
Therefore, \%hash is a reference to %hash, i.e., the whole hash, which appears to be what you intend to return in this case. \$hash{key} is a reference to a single element.
Where it gets tricky in your second question is that references are always scalars, regardless of what they refer to.
$hash_ref = \%hash
To get an element out of a hash that you have a reference to, you need to dereference it first. This is usually done with the -> operator, like so:
$hash_ref->{key}
Note that you use -> when you start from a reference ($hash_ref->{key}), but not when you start from an actual hash ($hash{key}).
(As a side note on question 2, don't prefix sub calls with & - just use authUser() instead of &authUser(). The & is no longer needed in Perl 5+ and has side-effects that you usually don't want, so you shouldn't get in the habit of using it where it's not needed.)
For question 3, if you're only going to check once, you may as well just loop over the array and check each element:
my $valid;
for my $username (#list_of_users) {
if ($login eq $username) {
$valid = 1;
last; # end the loop since we found what we're looking for
}
}
if ($valid) {
print "Found valid username $login\n";
} else {
print "Invalid user! $login does not exist!\n";
}
To be clear, Perl works with scalars or lists of them:
$scalar = 1;
#list = ( $scalar, $scalar, $scalar );
Each item of list may be accessed by index, e.g. $list[1].
You can also access items by name. This structure is called a hash: $hash{ name1 }
%hash = ( 'name1', $scalar, 'name2', $scalar, 'name3', $scalar )
But, as you can see, this is still a list. Notice the "()" around it.
And again, each item of the list can be only a scalar.
I have not seen this in any book, but the $ sign means one value and # means list of values.
In this example you have one value, so you use the $ sign:
$scalar = $hash{ name1 };
$scalar = $list[ 1 ];
In this next example you have a list of values, so you use "#":
#list2 = #list1; # copy all items
#list2 = #list[ 1, 3..5 ]; # copy four items with index 1,3,4,5
#list2 = #hash{ 'name1', 'name3' }; #copy two items with index 'name1', 'name2'
Perl has references. This is powerful tool.
$ref = \$scalar;
$ref = \#list;
$ref = \%hash;
$ref is also scalar, because it has only one value. To access to underlying data referred by this $ref, you should use a dereference.
$scalar = $$ref;
#list = #$ref;
%hash = %$ref;
But actually, you do not want the whole list or hash. You just want some item in them. For this, you use -> and either [] to tell Perl you want to access a list element, or {} to tell Perl you want to access a hash element:
$scalar = $ref->[ 1 ];
$scalar = $ref->{ name1 };
NOTICE: you're accessing one element, so you use the $ sign.
If you want list of elements from array or hashes, you use the # sign. For example:
#list = #$ref[ 1, 3..5 ];
#list = #$ref{ 'name1', 'name2' };
1st: $ref - returns reference to structure. $ says you get one value from variable 'ref'
2nd: #$ref - you dereference $ref. # says that you want to access the list of items by that reference.
3rd-a: you get '1,3,4,5' items from array (NOTICE: [])
3rd-b: you get 'name1', 'name2' items from hash (NOTICE: {})
But when you a get reference to hash or list and put this reference to another hash or array, we may create complex structures such as an array of hashes of hashes, or hash of arrays of hashes. Examples:
#list = ( 1, 2, 3, 4, 5 );
%hash = ( 'a', 1, b => 2 );
#list2 = ( \#list, \%hash, 3, 'y' );
%hash2 = ( name1 => \#list2, d => 4 );
%hash2 = ( 'name1', \#list2, 'd', 4 ); #same. no any difference.
$href = \%hash2;
=> - just quote left operand and put , after it.
If you want to access to one item of 'hash2':
$scalar = $hash2{ name1 };
$scalar = $href->{ name1 };
Using $href-> after dereferencing will mean %hash2.
If you want to access to two or more items of 'hash2':
#list = #hash2{ 'name1', 'd' };
#list = #$href{ 'name1', 'd' };
Using #$href after dereferencing will mean %hash2
IN DETAIL:
$scalar = $hash2{ name1 }; # <--- What does this mean???
$hash2 means we access one item of %hash2. Which is a reference to a list:
$list_ref = $hash2{ name1 };
$scalar = $list_ref->[ 1 ]; # <--- what we get here???
$list_ref means we access one item. ->[ means we access the list. Because $list_ref refers to #list2, we access \%hash. We can complete that in one step:
$scalar = $hash2{ name1 }->[ 1 ];
You may think here as you replace the text '$list_ref' by '$hash2{ name1 }'
We say that [ 1 ] refers to %hash. So to access one item of that hash we use $ again:
$hash_ref = $hash2{ name1 }->[ 1 ];
$scalar = $hash_ref->{ b };
$hash_ref means we access one item. ->{ means we access to hash. Because $hash_ref refers to %hash we access 2. We can complete that in one step:
$scalar = $hash2{ name1 }->[ 1 ]->{ b };
You again may think here as you replace text '$hash_ref' by '$hash2{ name1 }->[ 1 ]'. But hash2 here is %hash2. What about $href? Please remember this example:
$scalar = $hash2{ name1 };
$scalar = $href->{ name1 };
You may notice, if you access the item by ref you just add ->. Compare:
#l = ( 1, 2, 3, 4 );
$scalar = $l[ 1 ]; # to access to second item of #l list
$hr = \#l;
$scalar = $hl->[ 1 ]; # to access to second item of #l list
%h = #l;
$scalar = $h{ 1 };
$hr = \%h;
$scalar = $hr->{ 1 };
The type of bracket after -> will be [ for an array or { for a hash item.
What about $href?
$scalar = $hash2{ name1 }->[ 1 ]->{ b };
$scalar = $href->{ name1 }->[ 1 ]->{ b };
After the first dereference we do not require ->
$scalar = $hash2{ name1 }[ 1 ]{ b };
^-- first dereference
$scalar = $href->{ name1 }[ 1 ]{ b };
^--first dereference
Returning to your question: in Perl, you may pass a LIST of values to subs and return a LIST also.
sub test {
return #_;
}
Here we return all items we get.
return \%hash; # fn()->{ name1 }; # actually all these is list of one item
return \#list; # fn()->[ 1 ]; # so we may write: (fn())[0]->[ 1 ];
return $scalar; # fn(); # here also list of one item
return ( $scalar, \%hash, \#list );
(fn())[ 0 ];
(fn())[ 1 ]->{ name1 };
(fn())[ 2 ]->[ 1 ];
it is ok to use $hashTable{$login}, should I be using %hashTable{$login} or does it not matter?
Nope. You should use $ to access one item from %hashTable. $hashTable{$login} is right.
If you want to extract two logins you should use #:
#list = #hashTable{ 'login1', 'login2' };
# or
$l1 = 'login1';
$l2 = 'login2';
#list = #hashTable{ $l1, $l2 };
return \$hashTable{ $login };
Wrong. You return one item from a hash. So return $hashTable{ $login } is right.
2.Should my $authHash be really $authHash{ $something }, I am so confused on this
I suppose your %hashTable is a list of hashes keyed by $login. Like this:
$login1 = { name => 'Vasiliy', pass => 'secret' } # ref to hash
%login2 = ( name => 'Petrovich', pass => '^&UDHJ' ); # just a hash
%hashTable = (
vasya => $login1, # items are always refs!!!
piter => \%login2, # items are always refs!!!
)
So authUser sub will return a reference:
my $authHash = authUser( 'vasya' ); # & is not required at all
Because of $authHash, if the reference is to a hash you should use ->
if( $authHash->{ pass } eq $password ) {
...
}
But if your authUser is a parse config file and returns all users, you should to rename it to loadUsers and return a reference to the hash:
sub loadUsers {
....
return \%hashTable;
}
my $usersDB = loadUsers;
if( $usersDB->{ $login }->{ pass } eq $password ) {
print 'You have granged access';
}
else { ... }
Edit 2: Can anyone modify my code so that I can understand the answers better?
Nope. Read my tutorial. To understand how to write code you should do it yourself.
AS ADVICE
While you're a newbie:
always use hashref and listref.
always use -> to access items.
always use $ sigil as first char.
.
$list = [ 1, 2, 3 ];
$hash = { a => 1, b => 2 };
$list->[ 2 ];
$hash->{ b };
Exceptions will be when you access the whole array or hash:
#l = #$list;
%h = %$hash;
#l = keys %$hash;
#l = values %$hash;
You probably don't want to be doing this:
return \$hashTable{ $login };
You are returning a reference (pointer) to your hash.
Try just
return $hashTable{$login}
Which will return the account number.
Or if you really want a hash with a bunch of people in there then
return \$hashTable
is fine (don't add the {$login} part), but on the other side you need to be
dereferencing.
eg:
my $p = authUser()
if ($p->{'Dr. Brule'})
...
Notice the -> in there. It de-references the pointer you passed back.
I have a module with a new constructor:
package myClass;
sub new
{
my $class = shift;
my $arrayreference = shift;
bless $arrayreference, $class;
return $arrayreference;
};
I want to do something like:
foreach $ref (#arrayref)
{
$array1 = myClass->new($ref);
}
$array1 is being rewritten each time, but I want each element in the array to have a distinct object name (ex. $array1, $array2, $array3 etc.)
If you are working with a plural data structure (an array), then you need to store the result into a plural container (or multiple scalar containers). The idomatic way to do this is to use the map function:
my #object_array = map {myClass->new($_)} #source_array;
If you know that #source_array contains a fixed number of items, and you want scalars for each object:
my ($foo, $bar, $baz) = map {myClass->new($_)} #source_with_3_items;
I think you should use some hash or array to contain the objects.
foreach $ref (#arrayref)
{
push #array, myClass->new($ref);
$hash{$key++} = myClass->new($ref);
}
thus you can access them with $array[42] or $hash{42}.
There is essentially no name difference between $array[1] and $array1. There is a programmatic difference in that $array[1] can be "pieced together" and, under modern Perl environments $array1 can't. Thus I can write $array[$x] for any valid $x and get an item with a "virtual name" of $array.$x.
my #objects = map { MyClass->new( $_ ); } #data_array;
Thus, if you just want to append a number, you probably just want to collect your objects in an array. However, if you want a more complex naming scheme, one or more levels of hashes is probably a good way to go.
If you had a way to derive the name from the object data once formed, and had a method called name, you could do this:
my %object_map
= map { my $o = MyClass->new( $_ ); ( $o->name => $o ); } #data_array
;
Are you are trying to do it in place?
my #objects = (
{ ...args for 1st object... },
{ ...args for 2nd object... },
...
);
$_ = Class->new($_) for #objects;
However, you should avoid reusing variables like that.
my #object_data = (
{ ...args for 1st object... },
{ ...args for 2nd object... },
...
);
my #objects = map Class->new($_), #object_data;
I agree with Ade YU and Eric Strom, and have +1'd their answers: you should use one of their approaches. But what you ask is technically possible, using symbolic references, so for completeness' sake:
foreach my $i (0 .. $#arrayref)
{
no strict refs;
my $varname = 'array' . ($i + 1);
${$varname} = myClass->new($arrayref[$i]);
}