Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Autovivification trick

by blazar (Canon)
on Aug 12, 2006 at 10:56 UTC ( #567024=note: print w/ replies, xml ) Need Help??


in reply to Autovivification trick

Some more details: in this post someone asked how to "take strings like:"

/file.txt /a/file.txt /a/b/c /a/b/c/file.txt /z/m/w/file.txt

and "produce something like:"

%dir_hash( 'file.txt' => '', 'a' => { 'file.txt' => '', 'b' => { 'c' => { 'file.txt'
[snip]

In my reply I pointed out that there should be a module designed for exactly this kind of things, which I still fail to remember. (Hey, anyone here? Update: It's Data::Diver, thanks to tye!) But first of all I provided a minimal example to accomplish not exactly the same task, but a very close one; the original code is as follows:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %dirhash; while (<DATA>) { chomp; my $last=\%dirhash; $last=$last->{$_} ||= {} for split qr|/|; } print Dumper \%dirhash; __END__ /file.txt /a/file.txt /a/b/c /a/b/c/file.txt /z/m/w/file.txt

In it I have to compensate for perl not autovivifying in this case. Then Brian McCauley provided an alternative way, precisely suggesting that one do

my $last=\\%dirhash; $last=\$$last->{$_} for split qr|/|;

Instead, which is the Autovivification trick I'm "advertising" here.


Comment on Re: Autovivification trick
Select or Download Code
Re^2: Autovivification trick
by bobf (Monsignor) on Aug 13, 2006 at 00:11 UTC

    there should be a module designed for exactly this kind of things
    The only thing I found (during my admittedly limited search) was Data::Hierarchy - could that have been the one you were thinking of? It appears to be somewhat specialized and may not quite satisfy the same requirements that your snippet does, but it's the closest thing that I found.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://567024]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (10)
As of 2014-10-23 18:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (126 votes), past polls