Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

hash & arrays

by Spooky (Beadle)
on Nov 02, 2009 at 10:14 UTC ( [id://804434]=perlquestion: print w/replies, xml ) Need Help??

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

OK, ..lets say I do something like this: $hash{$userid} where $userid is a character string. How would I populate this with data elements that would be both numeric and alpha so that when I key in on say "ewh1234" I could pull all or a specific element within the array(?) - e.g., "ewh1234" may contain 'engineer, 23.4, 1.2, local' (4 data items within "ewh1234")? ..thanks

Replies are listed 'Best First'.
Re: hash & arrays
by cdarke (Prior) on Nov 02, 2009 at 10:26 UTC
    my %hash; $hash{ewh1234} = ['engineer', 23.4, 1.2, 'local']; # value for key ewh1234 is a reference to an anonymous array .... print "@{$hash{ewh1234}}\n"; # will print the array print "$hash{ewh12134}[1]\n"; # will print 23.4 ....
    Update: corrected typo (thanks Crackers2)
      What I tried doing (and failed) was the following: $hash{$empid} = $title, $adjst, $adjst2, $linex; "$linex" is actually an array with a number of variables and the other "substitution" variables are created earlier in the program. In executing this, Perl gave me the word "ARRAY" followed by an 0x hex string and then a 1 when I tried printing the first value. Can I not use the $ variables within the hash structure?
        Spooky,

        you can always explicitly define the type so instead of $linex (a pointer to an array) you can use "@{$linex}", my SCALAR is actually a list, honest.

        cheers

        John
Re: hash & arrays
by toolic (Bishop) on Nov 02, 2009 at 13:45 UTC
    Another approach is to use a HASHES OF HASHES which will allow you to name each of your elements.
    use strict; use warnings; use Data::Dumper; my %account = ( ewh1234 => { job => 'engineer', foo => 23.4, bar => 1.2, area => 'local' } ); print $account{ewh1234}{foo}, "\n"; print Dumper($account{ewh1234}); __END__ 23.4 $VAR1 = { 'bar' => '1.2', 'area' => 'local', 'foo' => '23.4', 'job' => 'engineer' };

      OP would probably find perldsc, perlref and Data::Dumper useful for playing around and getting to grips with things?

      Just a something something...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://804434]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (8)
As of 2024-04-18 07:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found