in reply to Parse data representing hash

Some advice, as requested:

So your script would work like this:

  1. Read line 1. @keychain is empty. Zero tabs, so you truncate it to zero entries (a no-op, coincidentally). Progress through $hash along your @keychain; since it's empty, you're still at the root. Add an entry for 'one' to the hash, add 'one' to @keychain.
  2. Read line 2. @keychain contains 'one'. One tab, so you truncate it to one entry (another no-op). Progress through $hash along your @keychain; you'll end up at $hash->{'one'}. Add an entry for 'two' to the hash, add 'two' to @keychain.
  3. Read line 3. @keychain contains 'one' and 'two'. One tab, so you truncate it to one entry (NOT a no-op this time). Progress through $hash along your @keychain; you'll end up at $hash->{'one'} again. Add an entry for 'three' to the hash, add 'three' to @keychain.
  4. Read line 3. @keychain contains 'one' and 'three'. And so on...

You get the idea - this is how I'd approach this.

Replies are listed 'Best First'.
Re^2: Parse data representing hash
by peterp (Sexton) on Jun 28, 2014 at 22:44 UTC

    Thank you for your advice, it correlates with what others have said by maintaining state in @keychain.

    When truncating I suppose the best approach be something along the lines of splice @keychain, $tabs_count; (update: nevermind this question, the example provided by choroba covers this)

      Yes, splice is likely the best approach. From its documentation:

      Removes the elements designated by OFFSET and LENGTH from an array [...] If LENGTH is omitted, removes everything from OFFSET onward.

      So with zero-based arary indexing, it really is as simple as splice @keychain, $tabs_count;, yes.

      You could also use an array slice, BTW, e.g. @keychain = @keychain[0 .. ($tabs_count - 1)];, but that's less elegant and idiomatic.

        Thanks again

        Just to add to these approaches, another approach suggested below is to do $#keychain = $tabs_count

        Regards