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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.