Perl multi hash from list - arrays

I have a list with some values which are connected. I need to create a hashmap with keys and values from the list and merge together. But i don't really know how to do it.
Input:
my #in =(
'mgenv/1_2_3/parent.dx_environment',
'mgenv/1_2_3/doc/types.dat');
Expected output:
"{ $env => { $ver => [ $file1, $file2, ... ] } }"
I've tried these:
(1)
my #sack_files = (
'mgenv/1_2_3/parent.dx_environment',
'mgenv/1_2_3/doc/types.dat');
my $sack_tree = {};
my %hash=();
for( my $i=0; $i<scalar #sack_files; $i++){
my #array = split(/[\/]+/,$sack_files[$i]);
for(my $i=0;$i<(scalar #array)-1;$i++){
my $first = $array[$i];
my $second = $array[$i+1];
$hash{$first}=$second;
}
# merge
}
(2)
use Data::Dumper;
my #sack_files = (
'mgenv/1_2_3/parent.dx_environment',
'mgenv/1_2_3/doc/types.dat',
);
my $sack_tree = {};
my %hash=();
for( my $i=0; $i<scalar #sack_files; $i++){
my #array = split(/[\/]+/,$sack_files[$i]);
nest(\%hash,#array);
}
In the second case I get an error because when the loop variable i=1 ,the key/values already exists so maybe i have to check the previously added key/values. But I don't really know how.
I would really appreciate any ideas.

Just use push to add new members to an existing array in a hash of hashes. You have to dereference the array reference with #{ ... }.
#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
my #sack_files = qw( mgenv/1_2_3/parent.dx_environment
mgenv/1_2_3/doc/types.dat
mgenv/1_2_3/doc/etc.dat
mgenv/4_5_6/parent.dx_environment
mgenv/4_5_6/doc/types.dat
u5env/1_2_3/parent.dx_environment
u5env/1_2_3/doc/types.dat
u5env/4_5_6/parent.dx_environment
u5env/4_5_6/doc/types.dat
);
my %hash;
for my $sack_file (#sack_files) {
my ($env, $ver, $file) = split m{/}, $sack_file, 3;
push #{ $hash{$env}{$ver} }, $file;
}
print Dumper \%hash;
output
$VAR1 = {
'mgenv' => {
'1_2_3' => [
'parent.dx_environment',
'doc/types.dat',
'doc/etc.dat'
],
'4_5_6' => [
'parent.dx_environment',
'doc/types.dat'
]
},
'u5env' => {
'4_5_6' => [
'parent.dx_environment',
'doc/types.dat'
],
'1_2_3' => [
'parent.dx_environment',
'doc/types.dat'
]
}
};

Related

PERL - Remove certain data form array after a symbol

my code looks like this
foreach ($id->{deleteids}) {
my #separated = split('_', $_);
push #rids, $separated[0];
}
on using Data::Dumper on $id->{deleteids} i get this
$VAR1 = [
'43-173739_cdfvgbvvd',
'43-173738_sddsvfdvfd',
'43-173737_sfvdfvdfvdf',
'43-173736_svdvdfvdfvdfvfdvfd'
];
My expected output of #rids that i want
$VAR1 = [
'43-173739',
'43-173738',
'43-173737',
'43-173736'
];
but on using Data::Dumper on #rids i always get
$VAR1 = 'ARRAY(0x3210010)';
Array references have different way to be called with, And as Zdim pointed you need to use a reference \#rids to dump array using Dumper
use strict;
use warnings;
use Data::Dumper;
my $id = { # creating a similar array like yours in a hash ref
deleteids => [
'43-173739_cdfvgbvvd',
'43-173738_sddsvfdvfd',
'43-173737_sfvdfvdfvdf',
'43-173736_svdvdfvdfvdfvfdvfd'
]
};
print Dumper($id->{deleteids});
my #rids;
foreach (#{$id->{deleteids}}) { # correct way to use array ref
my #separated = split('_', $_);
push #rids, $separated[0];
}
print Dumper(\#rids); # how to dump array using Dumper
Output:
# $id hash ref
$VAR1 = [
'43-173739_cdfvgbvvd',
'43-173738_sddsvfdvfd',
'43-173737_sfvdfvdfvdf',
'43-173736_svdvdfvdfvdfvfdvfd'
];
# #rids
$VAR1 = [
'43-173739',
'43-173738',
'43-173737',
'43-173736'
];
Following piece of code should do what you expect (remove undesired part)
foreach ($id->{deleteids}) {
s/_.*//;
push #rids, $_;
}

Convert an array of strings into a array of arrays of strings

My goal is to convert this
my #array=("red", "blue", "green", ["purple", "orange"]);
into this
my #array = ( ["red"], ["blue"], ["green"], ["purple", "orange"]);
Current test code:
my #array = ("red", "blue", "green", ["purple", "orange"] );
foreach $item ( #array ) {
#if this was Python, it would be as simple as:
# if is not instance(item, array):
# # item wasn't a list
# item = [item]
if(ref($item) ne 'ARRAY'){
#It's an array reference...
#you can read it with $item->[1]
#or dereference it uisng #newarray = #{$item}
#print "We've got an array!!\n";
print $item, "\n";
# keep a copy of our string
$temp = $item;
# re-use the variable but convert to an empty list
#item = ();
# add the temp-copy as first list item
#item[0] = $temp;
# print each list item (should be just one item)
print "$_\n" for $item;
}else{
#not an array in any way...
print "ALREADY an array!!\n";
}
}
# EXPECTED my #array=(["red"], ["blue"], ["green"], ["purple", "orange"]);
print #array , "\n";
foreach $item (#array){
if(ref($item) ne 'ARRAY'){
#
#say for $item;
print "didn't convert properly to array\n";
}
}
The comment about python maps pretty directly to perl.
my #array = ("red", "blue", "green", ["purple", "orange"] );
foreach $item ( #array ) {
#if this was Python, it would be as simple as:
# if is not instance(item, array):
# # item wasn't a list
# item = [item]
if (ref $item ne 'ARRAY') {
$item = [ $item ];
}
}
though using map as in Borodin's answer would be more natural.
I'm wondering why you want to do this, but it's
#array = map { ref ? $_ : [ $_ ] } #array
And please don't call arrays #array; that's what the # is for.
Your comment is ridiculous
#if this was Python, it would be as simple as:
# if is not instance(item, array):
# # item wasn't a list
# item = [item]
If you were familiar with Perl then you wouldn't need to ask the question. You must be aware that there is no one-to-one translation from Python to Perl. Python is much less expressive than either Perl or C, but I can't imagine you demanding a simple conversion to C.
Please get over your bigotry.
If you push the values to a new array, you don't need to do more than evaluate whether or not $item is an arrayref:
#! perl
use strict;
use warnings;
use Data::Dumper;
my #array=("red", "blue", "green", ["purple", "orange"]);
my #new_array;
foreach my $item (#array) {
if ( ref($item) eq 'ARRAY' ) {
push #new_array, $item;
}
else {
push #new_array, [$item];
}
}
print Dumper \#new_array;
Output from Dumper:
$VAR1 = [
[
'red'
],
[
'blue'
],
[
'green'
],
[
'purple',
'orange'
]
];
After a long day of learning more Perl than I ever thought/wanted to learn... here's what I think is a workable solution:
#! perl
use strict;
use warnings;
use Data::Dumper;
my %the_dict = (duts =>
{dut_a => {UDF => 'hamnet'},
dut_b => {UDF => [ '1', '2', '3', ]},
dut_c => {UDF => [ 'Z' ], }});
print Dumper \%the_dict;
foreach my $dut (keys %{$the_dict{duts}}) {
# convert the dut's UDF value to an array if it wasn't already
if ( 'ARRAY' ne ref $the_dict{duts}->{$dut}{UDF} ) {
$the_dict{duts}->{$dut}{UDF} = [ $the_dict{duts}->{$dut}{UDF} ];
}
# now append a new value to the array
push(#{$the_dict{duts}{$dut}{UDF}}, 'works');
}
print Dumper \%the_dict;
when run we see these print-outs:
$VAR1 = {
'duts' => {
'dut_a' => {
'UDF' => 'hamnet'
},
'dut_c' => {
'UDF' => [
'Z'
]
},
'dut_b' => {
'UDF' => [
'1',
'2',
'3'
]
}
}
};
$VAR1 = {
'duts' => {
'dut_a' => {
'UDF' => [
'hamnet',
'works'
]
},
'dut_c' => {
'UDF' => [
'Z',
'works'
]
},
'dut_b' => {
'UDF' => [
'1',
'2',
'3',
'works'
]
}
}
};

Iterative Hash Set up

I have the following array...
my #array=("100 2", "300 1", "200 3");
From this array I want to iteratively construct a hash.
Current Script:
my %hash;
foreach (#array) {
my #split = (split /\s+/, $_);
%hash = ("$split[0]", "$split[1]");
}
Current Output:
$VAR1 = {
'200' => '3'
};
This is not what I want. My goal is...
Goal Output:
$VAR1 = {
'100' => '2'
'300' => '1'
'200' => '3'
};
What do I need to do?
I am using: Perl 5, Version 18
Assigning to a hash—something you are doing each pass of the loop—replaces its contents. Replace
%hash = ("$split[0]", "$split[1]");
with
$hash{$split[0]} = $split[1];
Alternatively, replace everything with
my %hash = map { split } #array;

Push array to a certain hash within an array in Perl

I want to dynamically push values of hashes into an array of hashes in Perl.
I have this code block to create and push classHash to an array classList.
$courseName = <STDIN>;
$section = <STDIN>;
my $classHash = {};
$classHash->{courseName} = $courseName;
$classHash->{section} = $section;
push #classList, $classHash;
Now, I want to add a studentHash to the classHash.
for my $i ( 0 .. $#classList ) {
#I want to add the studentHash to a specific classHash in the classList
if($courseName1 eq $classList[$i]{courseName} && $section1 eq $classList[$i]{section}){
$studName = <STDIN>;
$studNum = <STDIN>;
my $studHash = {};
$studHash->{studName} = $studName;
$studHash->{studNum} = $studNum;
push #studList, $studHash;
push #{$classList[$i]}, \#studList; #but this creates an array reference error
}
}
Ignoring the interactive bits... here is how you can add the student to the class:
#!/usr/bin/env perl
use warnings;
use strict;
use Data::Dumper;
my #classList = (
{
courseName => 'Algebra',
section => 101,
students => [],
},
{
courseName => 'Geometry',
section => 102,
students => [],
},
);
my $studName = 'Alice';
my $studNum = 13579;
my $desiredClass = 'Geometry';
my $desiredSection = 102;
for my $class (#classList) {
if ($class->{courseName} eq $desiredClass and
$class->{section} eq $desiredSection) {
# Add student to the class
my $student = {
studName => $studName,
studNum => $studNum,
};
push #{ $class->{students} }, $student;
}
}
print Dumper \#classList;
# Printing out the students for each class
for my $class (#classList) {
my $course = $class->{courseName};
my $section = $class->{courseSection};
my $students = $class->{students};
my $total_students = scalar #$students;
my $names = join ', ', map { $_->{studName} } #$students;
print "There are $total_students taking $course section $section.\n";
print "There names are [ $names ]\n";
}
Output
VAR1 = [
{
'students' => [],
'section' => 101,
'courseName' => 'Algebra'
},
{
'students' => [
{
'studNum' => 13579,
'studName' => 'Alice'
}
],
'section' => 102,
'courseName' => 'Geometry'
}
];
There are 0 students taking Algebra section 101.
There names are [ ]
There are 1 students taking Geometry section 102.
There names are [ Alice ]

perl hash with array

I did same hash like this:
my %tags_hash;
Then I iterate some map and add value into #tags_hash:
if (#tagslist) {
for (my $i = 0; $i <= $#tagslist; $i++) {
my %tag = %{$tagslist[$i]};
$tags_hash{$tag{'refid'}} = $tag{'name'};
}}
But I would like to have has with array, so when key exists then add value to array.
Something like this:
e.g. of iterations
1,
key = 1
value = "good"
{1:['good']}
2,
key = 1
value = "bad"
{1:['good', 'bad']}
3,
key = 2
value = "bad"
{1:['good', 'bad'], 2:['bad']}
And then I want to get array from the key:
print $tags_hash{'1'};
Returns: ['good', 'bad']
An extended example:
#!/usr/bin/perl
use strict;
use warnings;
my $hash = {}; # hash ref
#populate hash
push #{ $hash->{1} }, 'good';
push #{ $hash->{1} }, 'bad';
push #{ $hash->{2} }, 'bad';
my #keys = keys %{ $hash }; # get hash keys
foreach my $key (#keys) { # crawl through hash
print "$key: ";
my #list = #{$hash->{$key}}; # get list associate within this key
foreach my $item (#list) { # iterate through items
print "$item ";
}
print "\n";
}
output:
1: good bad
2: bad
So the value of the hash element to be an array ref. Once you have that, all you need to do is push the value onto the array.
$hash{$key} //= [];
push #{ $hash{$key} }, $val;
Or the following:
push #{ $hash{$key} //= [] }, $val;
Or, thanks to autovivification, just the following:
push #{ $hash{$key} }, $val;
For example,
for (
[ 1, 'good' ],
[ 1, 'bad' ],
[ 2, 'bad' ],
) {
my ($key, $val) = #$_;
push #{ $hash{$key} }, $val;
}

Resources