Hen_true has asked for the wisdom of the Perl Monks concerning the following question:

I have the following data which I need to store. how do i use the hash to store the data so that i can use it whenever i want to use it. the data is as follows:

S ::= ASB S ::= #$ S ::= $ A ::= a A ::= aSbN B ::= b

I want to be able to use these data even if they are provided in an in put file.

Replies are listed 'Best First'.
Re: How do I use a hash to store my data
by mirod (Canon) on Nov 09, 2000 at 15:06 UTC
    You can't simply have the left part of each rule be the keys to the hash and the right part as the values, as you have several S's and A's. That means what would be the obvious choice for hash keys turns out to be non-unique.

    So one solution is to just use the right part as the keys and the left as the values.

    #!/bin/perl -w use strict; my %hash; while( <>) { # note: the left part should be just one character $hash{$2}= $1 if( m/^\s*(.)\s*::=\s*([^\s]*)\s*$/); } while( my($key, $value)= each %hash) { print "/$key/ ::= /$value/\n"; }

    Now if you want the left part as the keys you want the values of the hash to be array refs, each array containing the various expressions. Using the hash is also a little more tricky. You can use perl -d (the Perl debugger) to figure out the structure of the hash while the program is running.

    #!/bin/perl -w use strict; my %hash; while( <>) { my($key, $value)= m/^\s*(.)\s*::=\s*([^\s]*)\s*$/; $hash{$key} ||= []; # create an array ref if needed push @{$hash{$key}}, $value; # add to the array } while( my($key, $values)= each %hash) { # the values are in @{$values} print "/$key/ ::= /", join( '/', @{$values}), "/\n"; }
Re: How do I use a hash to store my data
by Doraemon (Beadle) on May 11, 2004 at 09:50 UTC
    To take the right side of ::= as key is not so wise decision, because it is not unique.
    My suggestion, create new data structure :
    %hash_of_hash = (); $key = 'S'; $new_data = {}; $new_data{'1'} = 'ASB'; $new_data{'2'} = '#$'; $new_data{'3'} = '$'; $hash_of_hash{$key} = $new_data; # repeat for other data....
Re: How do I use a hash to store my data
by davorg (Chancellor) on Nov 09, 2000 at 14:53 UTC

    You're going to need to explain a bit more about what you want to do with this data before anyone can help you.

    In the meantime, it might help if you took a look at the perldoc perldsc man page.