Note that there are some explanatory texts on larger screens.

plurals
  1. PODeleting and adding Hash and Array references in Perl
    primarykey
    data
    text
    <p>Continuing on from my <a href="https://stackoverflow.com/questions/4558981/dynamically-recursively-building-hashes-in-perl">previous question</a>, I ran into another problem down the road. I realized not only should there be hashes within hashes, there can also be arrays within hashes. So the paths would be something like </p> <pre><code>one/two/three one/two[]/three one/two/four one/two[]/four </code></pre> <p>i.e. the hash is supposed to contain the array will always have a <code>[]</code> as its suffix. According to the script I'm using (slightly modified version of the answer of my previous question), the above paths would result in: </p> <pre><code>one =&gt; { two =&gt; { three =&gt; "", four =&gt; "", } two[] =&gt; [ { three =&gt; "", four =&gt; "", } ] } </code></pre> <p>The script I'm using is: </p> <pre><code># !/usr/bin/perl use Data::Dumper; sub insert { my ($ref, $head, @tail) = @_; if ( @tail ) { if( $head !~ /^(.*)(\[\])$/ ) { insert( \%{$ref-&gt;{$head}}, @tail ); } else { my %newhash = (); unshift(@{$ref-&gt;{$1 . $2}}, %newhash); insert( \%{$ref-&gt;{$1 . $2}[0]}, @tail ); } } else { $ref-&gt;{$head} = ''; } } my %hash; chomp and insert \%hash, split( '/', $_ ) while &lt;&gt;; print Dumper %hash; </code></pre> <p>What I'd like to do, is once I find <code>two[]</code>, I'd like to delete <code>two</code> and add it to the array of <code>two[]</code> (if <code>two</code> exists) and then rename key <code>two[]</code> to <code>two</code>.</p> <p>So the end result would look something like:</p> <pre><code>one =&gt; { two =&gt; [ { three =&gt; "", four =&gt; "", }, { three =&gt; "", four =&gt; "", } ] } </code></pre> <p>So I tried adding checks within the <code>if else</code> for checking keys with or without <code>[]</code> suffixes but I got a range or errors like <code>[$variable] is not a valid HASH reference</code>, etc. How would one go about checking the type of the variable (eg <code>$ref-&gt;{$head} is array?</code>) and deleting and renaming keys of the hash efficiently? </p> <p>Thanks. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload