[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Autovivifying (was Re: HUMOR: you have to see this code!)



>>>>> "RJK" == Ronald J Kimball <rjk@linguist.dartmouth.edu> writes:

  RJK> On Mon, Nov 08, 1999 at 09:37:45AM -0500, John Porter wrote:
  >> Matthew Bafford wrote:
  >> > 
  >> > 9) Creating an element in an array to find out if it exists:
  >> > 
  >> >         if(!$_[1]){
  >> 
  >> Nope.  Array elements don't autovivify like hashes.
  >> 

  RJK> Hash elements don't autovivify like hashes either.

  RJK> _References_ autovivify.  Regardless of the data structure.

to clarify, assignments to dereferenced references (which are not
previously defined) autovivify. just dereferencing them doesn't.

  DB<12> p $r

  DB<13> ${$r} = 3		# autovivify $r

  DB<14> p $r
SCALAR(0x196b58)		# it is a ref
  DB<15> $s = 'aaa';

  DB<16> ${$s} = 55		# symbolic ref

  DB<17> p $s       		# $s is not autovivified
aaa

one of the most common uses for autovivication is pushing onto a ref in a
data structure:

	if ( blah ) {

		push @{ $self->{'array' } }, 'more blah' ;
	}

and remember, a multilevel hash where the last element doesn't exist
(even when using exists) will autovivify all intermediate levels. that
is because you are doing an implied assignment of a hash ref to each
undefined hash element so you can access the next lower level.

 DB<21> x $top
0  undef
  DB<22> exists $top->{foo}{bar}{key}

  DB<23> x $top                      
0  HASH(0x2a9c44)
   'foo' => HASH(0x2c68e8)
      'bar' => HASH(0x2c68c4)
           empty hash


uri

-- 
Uri Guttman  ---------  uri@sysarch.com  ----------  http://www.sysarch.com
SYStems ARCHitecture, Software Engineering, Perl, Internet, UNIX Consulting
The Perl Books Page  -----------  http://www.sysarch.com/cgi-bin/perl_books
The Best Search Engine on the Net  ----------  http://www.northernlight.com

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe