Getting a fragment through an array of hash links in Perl

I have a Perl related question regarding complex data structures. I am running version 5.8.8 of Perl on a Linux server (Centos v5), hosting Apache. I will interrogate the MS-SQL database. I am using the "DBI" Perl module.

I have an SQL query result table encoded as a reference to an array of hash links. Therefore, each row in the table is an array element containing a hash link obtained using the fetchrow_hashref command of the DBI module. The keys of each hash correspond to the column headings and the values ​​corresponding to a specific cell in the table under this column heading.

What I would like to do is get an array of column data. It seems that the DBI documentation describes how to get these columns, but for me they are a bit opaque, and it would be nice to know how to get a slice through an array of hash links as an exercise in understanding how perl referencing / disclosure works.

So basically, given this:

my %datarow1 = {"firstname"=> "dave", "bar"=>"smith"};
my %datarow2 = {"firstname"=> "john", "bar"=>"doe"};
my %datarow3 = {"firstname"=> "kim", "bar"=>"kardashian"};

It is called like this:

my @rows = (\%datarow1, \%datarow2, \%datarow3);
my $rowsref=\@rows;

How to get this array ?:

("dave", "john", "kim")

I tried this:

my @columndata=@$rowsref->[0]{"firstname"}

but this only gives me the first cell in the column (ie an array containing one dave element). There must be an elegant way to do this in one line - if the gurus-gurus could help me because of you, I would really appreciate it.

thank

Cj

+4
source share
3 answers

Where to begin:

, :

my %datarow1 = {"firstname"=> "dave", "bar"=>"smith"};

- , :

( 'HASH(0x7f4ef0545e18)' => undef )

, , .

:

my %datarow1 = ("firstname"=> "dave", "bar"=>"smith");

:

use strict;
use warnings; 

, .

-

: " Hash, ?"

, - :

my $h_ref = { a => b };
# get key 'a'
my $a = $h_ref->{a}; 

, . - map builtin:

use strict;
use warnings; 

my %datarow1 = ("firstname"=> "dave", "bar"=>"smith");
my %datarow2 = ("firstname"=> "john", "bar"=>"doe");
my %datarow3 = ("firstname"=> "kim", "bar"=>"kardashian");

my @rows = (\%datarow1, \%datarow2, \%datarow3);
my $rowsref=\@rows;
my @firstnames = map { $_->{firstname} } @$rowsref; 
# dave john kim
+6

use strict; use warnings;, :

, "script" "

, :

my %datarow1 = ("firstname"=> "dave", "bar"=>"smith");

:

my @columndata = map {$_->{"firstname"}}  @$rowsref;
say Dumper\@columndata;
+3

[Edit: already answered, but I recommend this for TIMTOWDI-ness]

With the help perl5.22.0you can also:

use experimental 'refaliasing';

for \my %hash (\%datarow2, \%datarow1, \%datarow3 ) { 
      say $hash{"firstname"} ; 
}
0
source

Source: https://habr.com/ru/post/1629236/


All Articles