Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Extracting values from hash

by Sun751 (Beadle)
on Jul 01, 2009 at 08:21 UTC ( [id://776344]=perlquestion: print w/replies, xml ) Need Help??

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

To get rid of too many variables I used hash to record all my records in it,
sub initilize_config { my ($HR_config,$file) = @_; open (my $fr, '<', "$file") || die "Unable to open configuration f +ile: $file $!"; while (my $line = <$fr>) { $line =~ tr/\r\n//d; next unless $line; if ($line =~ /=/) { my ($key,$val)=$line=~ /^(.*?)=(.*?)$/; $$HR_config{$key} = $val; } } }
the key of the hash is constant where as value always change so in some subroutine if I want to extract and use the value of some key, suppose "xyz". How can that be done? Can any one suggest me please!!! Cheers

Replies are listed 'Best First'.
Re: Extracting values from hash
by moritz (Cardinal) on Jul 01, 2009 at 08:25 UTC
    See perldata and perlreftut, you can access the value of a hash reference like this: $HR_config->{xyz}.
Re: Extracting values from hash
by jrsimmon (Hermit) on Jul 01, 2009 at 11:39 UTC
    Here's a short little script that you can play with to see how this works.

    use strict; use warnings; my %HR_config= (); my $cfgFile = "c:\\temp\\cfg.ini"; &initiliaze_config(\%HR_config, $cfgFile); my (@retVals) = &retrieve_config(\%HR_config); print "Values from the returned array:\t@retVals\n"; my @keys = keys(%HR_config); print "Keys from the populated hash:\t@keys\n"; my @hashVals = map ($HR_config{$_}, @keys); print "Values from the populated hash:\t@hashVals\n"; sub initiliaze_config { my ($HR_config,$file) = @_; open (my $fr, '<', "$file") || die "Unable to open configuration f +ile: $file $!"; while (my $line = <$fr>) { $line =~ tr/\r\n//d; next unless $line; if ($line =~ /=/) { my ($key,$val)=$line=~ /^(.*?)=(.*?)$/; $$HR_config{$key} = $val; } } } sub retrieve_config { my $HR_config = pop(@_); my @values = (); foreach my $key (keys(%{$HR_config})){ my $value = $HR_config->{$key}; push(@values, $value); } return (@values); }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (None)
    As of 2024-04-25 01:51 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found