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

Hi all .I need to add employee details to a hash,i mean i need employe id as key and i need to move all other details to be value storing them in a list. i tried this.

%database; @employee_details=($employee_name, $employee_salary,$employee_ph,"\n" +); $database{$employee_id}=(@employee_details);
When i tried this the size of array is stored in the value. I tried passing (\@employee_details) i.e reference of list but i cant access the list.

Replies are listed 'Best First'.
Re: Tring to write script to add and get employee details to hash
by toolic (Bishop) on Mar 27, 2015 at 13:29 UTC
    This (ugly) code seems to "work" for me:
    my($employee_name,$employee_salary,$employee_ph,$employee_id) = 5..8; %database; @employee_details=($employee_name, $employee_salary,$employee_ph,"\n" +); $database{$employee_id}=(\@employee_details); use Data::Dumper; $Data::Dumper::Sortkeys=1; print Dumper(\%database); __END__ $VAR1 = { '8' => [ 5, 6, 7, ' ' ] };

    Tip #1 from the Basic debugging checklist: warnings

Re: Tring to write script to add and get employee detials to hash
by Anonymous Monk on Mar 27, 2015 at 13:35 UTC

    Have a look at "hashes of arrays" in perldsc, that gives lots of code examples on how to access data structures like that, and see also perlreftut. For example:

    my %database; my $employee_id = 961; my $employee_name = "Anonymous Monk"; my $employee_salary = "fun"; my $employee_ph = 5.5; my @employee_details = ($employee_name,$employee_salary,$employee_ph); $database{$employee_id} = \@employee_details; print "$database{961}[0]: $database{961}[1]\n"; __END__ Anonymous Monk: fun

    (Why is "\n" part of the employee's details in your code?)

    But then again, this kind of data seems more appropriately stored in a hash of hashes (also described in perldsc):

    my %database; my $employee_id = 961; $database{$employee_id} = { name => "Anonymous Monk", salary => "fun", ph=> 5.5 }; print "$database{961}{name}: $database{961}{ph}\n"; __END__ Anonymous Monk: 5.5

      Thanks for the reply. How can i store this hash into a text file and how to access the hash from text file using file handle

        Does the text file need to be in a particular format? If not, you're free to choose any serialization format you like, be it XML, YAML, JSON, or something else. Personally, I might recommend YAML, as it maps to Perl data structures better than JSON and is less verbose than XML. See for example YAML::XS.