in reply to Re^2: Need to find unique values in hash
in thread Need to find unique values in hash
Actually its a simple hash but not anonymous hash.
I have expanded on Veltro's response.
Given the simple structure provided, I was able to back-engineer the hash. I then used the Data::Dumper->Dump method that allows names to be stored, following the documentation perldoc Data::Dumper.
There are slight differences in the way the storage occurs. The named hash gets stored as a hash, whereas the VAR structures are stored anonymously. Notice the arguments to Data::Dumper->Dump are each in anonymous arrays. You may need to play around with the sigils to the arguments a little to get the desired output.
#!/usr/bin/perl -T # use v5.22 for <<$datafh>> use strict; use warnings; use feature qw/state/; use Data::Dumper; my $data = get_input_data(); open my $datafh, '<', \$data or die 'not getting it'; my %HASH; while(my $line = <$datafh> ){ state $kv; state $current_key; chomp($line); if( $line =~ s/\A\$VAR\d+\s\=\s(\'|\[)// ){ $kv = $1; if( $kv eq '\'' ){ $line =~ s/\'\;\Z//; $current_key = $line; } next; }else{ next if $line =~ m/\A\s+\]\;\Z/; $line =~ s/\A\s+\'(.*)\'\,?\Z/$1/x; push @{ $HASH{ $current_key } }, $line; } } print 'Dumper with VAR',"\n"; print Dumper(\%HASH); =head output1 $VAR1 = { '3|1' => [ 'user', 'user', 'user', 'admin', 'admin', 'manager' ], '2|7' => [ 'system' ] }; =cut print 'Dumper with names',"\n"; print Data::Dumper->Dump([\%HASH],[qw(*HASH)]); =head output2 %HASH = ( '3|1' => [ 'user', 'user', 'user', 'admin', 'admin', 'manager' ], '2|7' => [ 'system' ] ); =cut sub get_input_data{ q{$VAR1 = '3|1'; $VAR2 = [ 'user', 'user', 'user', 'admin', 'admin', 'manager' ]; $VAR3 = '2|7'; $VAR4 = [ 'system' ]; }; }
fun note: output1 and output2 appear to sort in the same order after a few manual runs, although which key is top is random, they both show keys in same sorting order as each other. Perhaps an internal optimisation?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Need to find unique values in hash
by dipit (Sexton) on Feb 05, 2019 at 08:06 UTC |