Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Dynamically create the hash reference

by k_manimuthu (Monk)
on Oct 07, 2015 at 10:16 UTC ( [id://1144042]=perlquestion: print w/replies, xml ) Need Help??

k_manimuthu has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

I am trying to create dynamic references in a recursion function. Below I place code which I try, and it return '{}' only. How to get the initial level reference in else part?

use Data::Dumper; sub insert { my ($ref, $head, @tail) = @_; return unless ( @tail ); if ( @tail and $head ne 'break') { insert( \%{$ref->{$head}}, @tail +) } else { # Here $ref gives '{}' value only. # How to get values of previous head values (ie. f1,f2,f3) print "\n==>", Dumper $ref; # More commands . . . #insert( \%{$ref->{f1}}, @tail ) } } my %hash; while (<DATA>) { chomp and insert \%hash, split( '/', $_ ) ; } print "\nDump\n", Dumper %hash; __DATA__ f1/f2/f3/f4/break/f1/f2/f5/break/f1/f2/f6

Replies are listed 'Best First'.
Re: Dynamically create the hash reference
by choroba (Cardinal) on Oct 07, 2015 at 11:09 UTC
    In order to be able to return back to the top of the hash, you have to include the top reference to the arguments.
    #!/usr/bin/perl use warnings; use strict; use Data::Dumper; sub insert { my ($top, $ref, $head, @tail) = @_; return unless @tail; if ('break' eq $head) { insert($top, $top, @tail); } else { # Don't overwrite existing paths. $ref->{$head} = {} unless exists $ref->{$head}; insert($top, $ref->{$head}, @tail); } } my %hash; while (<DATA>) { chomp; # Add a dummy end not to throw the last entry away. insert(\%hash, \%hash, split(m=/=), '/.'); } print "\nDump\n", Dumper(\%hash); __DATA__ f1/f2/f3/f4/break/f1/f2/f5/break/f1/f2/f6

    See also Data::Diver.

    Update: Data::Diver example added.

    while (<DATA>) { chomp; for my $path (split m=/break/=) { DiveVal(\%hash, split m=/=, $path); } }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      @choroba You point me into right direction. Thanks a lot.
Re: Dynamically create the hash reference
by Discipulus (Canon) on Oct 07, 2015 at 10:31 UTC
    hello k_manimuthu

    i'm not sure to well understand your question.. what is the desired hash that you want to pull from that data?

    L*
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1144042]
Front-paged by Arunbear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-25 10:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found