develooper Front page | perl.beginners | Postings from April 2010

Re: how to create a hash on the fly

Thread Previous | Thread Next
From:
Uri Guttman
Date:
April 14, 2010 22:25
Subject:
Re: how to create a hash on the fly
Message ID:
87pr21l229.fsf@quad.sysarch.com
>>>>> "r" == raphael()  <raphael.japh@gmail.com> writes:

  r> # abc      <-- this_should_be_hash_name

  r> {space} "random_name_or_number"  "date"  "other_things_1" "other_things_2"
  r> {space} "random_name_or_number"  "date"  "other_things_1" "other_things_2"

  r> How can I create a hash by the name that matches

  r> m/^#(?:\s+)?(\S+)$/

  r> The hash should be created by the name of "$1" i.e (\S+)$
  r> like if "$1" is 'abc' the hash should be %abc which will later be filled by
  r> keys & values
  r> that are matched in the next line. Thus hash should be created beforehand.

this is called symbolic references and it is a very bad
idea. effectively you would be using perl's symbol table as a data
structure which gains nothing, can cause major problems (everything is
global), and can also slow you down.

the proper solution is to use a hash to hold these hashes. this is
cleaner, safer, allows you to isolate this data, pass it around easily,
reclaim its memory when it is not being used anymore, etc.

notice how many bad things there are about symbolic references and how
many good things about multilevel hashes? also note that symrefs are not
allowed under strict (which you should be using all the time).

so just declare a top level hash like this:

my %top_data ;	# pick a better name

and then just assign into it the data you want with an anonymous hash:

	$top_data{ $1 } = { $2 => $3 } ;

or use whatever regex grabs you want.

read these docs for more on this:

	perlreftut
	perldsc
	perllol

uri

-- 
Uri Guttman  ------  uri@stemsystems.com  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About