SPUG: Auto-vivification question

Chris Wilkes cwilkes at singingfish.com
Thu Oct 5 12:36:09 CDT 2000


After gaining some insight at the last SPUG meeting on why this feature
exists, I took up Mark-Jason's suggestion to do something about it.

I decided to just look into getting around this issue in perl as I don't
know C and it would take me forever to even find the right section in the
perl source.

My little trick involves copying the hash to a temporary variable and then
doing the exists tests on it.  No brain surgery here.  It works for multi
level hashes, but not for arrays of hashes or other complex data
structures.

Let me know if this looks correct and how I can make this more
seemless.  I don't mind calling the subroutine exists_nav() but I don't
like the way I specify the keys to look at.

Chris


#!/usr/bin/perl

use strict;

my ($ref, $retcode);

undef $ref;
if (exists $ref->{"Some key"})      { }
print "'$ref'\n"; # prints hash -- this is bad

undef $ref;
$retcode = exists_nav($ref, "Some key", "key 2");
print ( ($retcode) ? "exists\n" : "does not exist\n");
print "'$ref'\n"; # prints nothing

undef $ref;
$ref->{"Some key"}{"key 2"} = 1;
$retcode = exists_nav($ref, "Some key", "key 2");
print ( ($retcode) ? "exists\n" : "does not exist\n");
print "'$ref'\n"; # prints HASH as it does exist

undef $ref->{"Some key"}{"key 2"}; # not sure if this is right
$retcode = exists_nav($ref, "Some key", "key 2");
print ( ($retcode) ? "exists\n" : "does not exist\n");
print "'$ref'\n"; # still prints hash, is this a problem?

sub exists_nav {
  my ($a, @keys) = @_;
  my $b = $a;
  foreach (@keys) {
    return 0 unless (exists($b->{$_}));
    $b = $b->{$_};
  }
  return 1;
}



 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
  Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/





More information about the spug-list mailing list