Reputation: 13
I was looking for some sort of solution if the following setup can be interpreted as formal declaration of the variables , if possible. What i have is :
my $str_1 = "{cow}" ;
my $str_2 = "{cow}{black}{tasty_milk}";
what i want is :
(Based on above variable string is it possible to initialize a hash directly, something like :)
my %hash=();
$hash."*some operator* on $str_i" = 'Initialized' ;
This "some operator" should make $hash to recognize as hash as it was declared earlier. i.e Input specific hash initialization.
PS: I don't want to write a function that will work on the string and get all information to initialize the hash.
Upvotes: 1
Views: 103
Reputation: 386351
Say you had the following input instead:
my @path = qw( cow black tasty_milk );
Then you can use the following:
use Data::Diver qw( DiveVal );
DiveVal(\%hash, map \$_, @path) = 'value';
So, with Data::Diver, we get:
use Data::Diver qw( DiveVal );
$str =~ /^(?:\{\w+\})+\z/
or die("Unrecognized format");
my @path = $str =~ /(\w+)/g;
DiveVal(\%hash, map \$_, @path) = 'value';
Without a module:
sub dive_val :lvalue { my $p = \shift; $p = \( $$p->{$_} ) for @_; $$p }
$str =~ /^(?:\{\w+\})+\z/
or die("Unrecognized format");
my @path = $str =~ /(\w+)/g;
dive_val(\%hash, @path) = 'value';
Upvotes: 4
Reputation: 5927
Try the following with anonymous hash
use Data::Dumper;
use warnings;
use strict;
my $str_2 = "{cow}{black}{tasty_milk}";
my %hash;
my $ref =\%hash;
my $val;
my $lp = () = $str_2=~m/\}/g; #count the number of }
my $i = 1;
while($str_2=~m/\{(\w+)\}/g)
{
$val = $1;
last if ($lp == $i);
$ref->{$val} = {}; #make the anonymous hash
$ref = $ref->{$val}; #add the data into anonymous hash
$i++;
}
$ref->{$val} = "value"; #add the last value
print Dumper \%hash;
Upvotes: 0