PERL dynamically match arrays based on unique key - arrays

I'm trying to compare 2 huge arrays and want to use map. I am using unique key concept here to match the indexes.
My Arrays:
my #array1 = ( ['a','b','c','d'], ['e','f','g','h'], ['i','j','k','l'], ['m','n','o','p'], ['q','r','s','t']);
my #array2 = ( ['r','q','s','t'], ['b','a','c','d'], ['n','m','o','p'], ['f','e','g','h'], ['j','i','k','l']);
My unique Keys:
my #uk1 = (0,2,3);
my #uk2 = (1,2,3);
These arrays will be huge in size, over 30,000 indexes in each with over 20 elements in each index.
So effectively i create a map where
for ( my $j = 0; $j <= $#array1 ; $j++ )
{
my searchString;
for ( my $k = 0; $k <= $#uk1; $k++ )
{
if ( $k != 0 )
{
$searchString .= ","
}
$my searchString .= $array1[$j][$uk[$k];
}
my #result = map { $_ }
grep { join (",",$array2[$_][1],$array2[$_][2],$array2[$_][3]) ) =~ join(",",$array1[$j][0],$array1[$j][1],$array1[$j][2]) }
0 .. $#array;
}
returns matched indexes.
My problem is, how do i make this dependant on the unique keys? as the length of the unique key will keep changing and as far as i know i cannot dynamically create the $array2[$_] join part.
Hope my question is clear enough.
I want to have the logic that compares
$array1[$uk1[0]],$array1[$uk1[1]],$array1[$uk1[2]] and so on (depending on the number of keys in UK) with
$array2[$uk2[0]],$array2[$uk2[1]],$array2[$uk2[2]].......

Perhaps,
my #array1 = ( ['a','b','c','d'], ['e','f','g','h'], ['i','j','k','l'], ['m','n','o','p'], ['q','r','s','t']);
my #array2 = ( ['r','q','s','t'], ['b','a','c','d'], ['n','m','o','p'], ['f','e','g','h'], ['j','i','k','l']);
my #result;
for my $i (0 .. $#array1) {
push #result,
map { [$i, $_] }
grep {
"#{ $array1[$i] }[1,2,3]" eq "#{ $array2[$_] }[0,2,3]"
}
0 .. $#array2;
}
use Data::Dumper; print Dumper \#result;
output
$VAR1 = [
[
0,
1
],
[
1,
3
],
[
2,
4
],
[
3,
2
],
[
4,
0
]
];

What you want to use is an array slice:
But lets also make life easier:
for my $sample ( #array1 )
{
my $test= join(",", #$sample[#uk1]) ;
my #result = grep { $_ eq $test } map { join(",", #$_[#uk2] ) } #array2 ;
say "huzzah" if #result ;
}
Perl lets you specify multiple elements from an array via the "array slice":
my #list= ('a', 'b', 'c', 'd') ;
my #pieces= #list[1,3] ;

Related

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;

Perl: Rearrange array based on element value

What would be the most efficient way to rearrange the array elements so that they are ordered & place with the corresponding index value (minus one)? The $dat variable being the max number of elements (which is never exceeded in the array but may or may not be present).
$dat = 14;
my #array = (1, 12, 14, 7, 8, 4)
In other words:
my #new_array = (1, undef, undef, 4, undef, undef, 7, 8, undef, undef, undef, 12, undef, 14);
***EDIT****
Fuller code snippet:
foreach $auth (keys %activity) {
my #value = #{ $activity{$auth} };
#value = uniq #value;
#value = sort #value;
s/^0// for #value;
my $count = scalar(grep $_, #value);
my $dat = max( #value );
#{$activity{$auth}} = #value;
}
Simple and fast (duplicates may occur in the original):
my #new_array;
$new_array[$_ - 1] = $_ for #array;
In-place (duplicates not allowed in original):
for (my $i = #array; $i--; ) {
my $j = $array[$i]-1;
if ($i < $j) {
$array[$j] = $j+1;
$array[$i] = undef;
}
elsif ($i > $j) {
#array[$i, $j] = #array[$j, $i];
redo;
}
}
In-place (duplicates may occur in the original):
for (my $i = #array; $i--; ) {
my $j = $array[$i]-1;
if ($i < $j) {
$array[$j] = $j+1;
$array[$i] = undef;
}
elsif ($i > $j) {
if ($array[$j] == $j+1) {
$array[$i] = undef;
}
else {
#array[$i, $j] = #array[$j, $i];
redo;
}
}
}
pop(#array) while #array && !defined($array[-1]);
You can create an new array with all values defined after finding the maximum value in the first, then in this new array undefine any value which is not in the first:
use strict;
use warnings;
use Data::Dumper;
my #array = ('1', '4', '3');
my $max = (sort { $b <=> $a } #array)[0]; #should be 4
print Dumper(\#array);
my #new_arr;
foreach my $index (0 .. ($max - 1)) {
$new_arr[$index] = ($index + 1);
#Array should be fully populated, #new_arr = ('1', '2', '3', '4');
$new_arr[$index] = 'undef' unless (grep {$_ eq $new_arr[$index]} #array);
#Values not in the original array should be set to undef
}
# #new_arr should be (''1', 'undef', '3', '4')
print Dumper(\#new_arr);
Output:
$VAR1 = [
'1',
'4',
'3'
];
$VAR1 = [
1,
'undef',
3,
4
];

Perl multi hash from list

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'
]
}
};

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;
}

perl hash of arrays

I am trying to access elements of an array which is part of a hash.
for my $idx ( 0 .. $#vss ) {
push (#{$vsnhash->{$vss[$idx]}}, $vsports[$idx]);
}
print Dumper(\%$vsnhash);
($VAR1 = {
'name2' => [
'8001',
'8002'
],
'name1' => [
'8000'
]
};
I an able to access the keys with a foreach loop:
foreach my $key ( keys %$vsnhash ) {
print "$key\n";
}
How do I access the array of port numbers ('8001' , '8002') within the hash?
Thank you for the help!
while (my ($k, $v) = each %$vsnhash) {
print "$k: #$v\n";
}
foreach my $key ( keys %$vsnhash ) {
print "$key\n";
foreach my $port (#{$vsnhash->{key}}){
print "Port $port\n";
}
}
$vsnhash{name2}->[0]; #8001
$vsnhash{name2}->[1]; #8002
$vsnhash{name1}->[0]; #8000
Code wise:
foreach my $key (sort keys %vsnhash) {
foreach my $index (0..$#{$key}) {
print "\$vsnhash{$key}->[$index] = " . $vsnhash{$key}->[$index] . "\n";
}
}
The $#{$key} means the last entry in the array #{$key}. Remember that $key is a reference to an array while #{$key} is the array itself.

Resources