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

In below example I am wondering if there is any way to preserve the existing elements and add new element to hash in each loop?
#! /usr/bin/perl env use strict; use warnings; my $hash; while(my $line = <DATA>) { my ($key, $val)=split(':',$line); $hash = ini($key,$val); } foreach (keys %$hash) { print "$_\n"; } sub ini { my ($key,$val)=@_; my %ini_hash; $ini_hash{$key}=$val; return \%ini_hash; } __DATA__ Name: Sam Address: Mascot Ph.No: 123321
Cheers,

Replies are listed 'Best First'.
Re: Hash Add new elements through loop
by GrandFather (Saint) on Mar 24, 2010 at 00:01 UTC

    Why jump through all those hoops? On the face of it all you need is:

    #! /usr/bin/perl env use strict; use warnings; use Data::Dumper; my %record; while (my $line = <DATA>) { chomp $line; my ($key, $val) = split /:\s*/, $line, 2; $record{$key} = $val if defined $val; } print Dumper (\%record); __DATA__ Name: Sam Address: Mascot Ph.No: 123321

    Prints:

    $VAR1 = { 'Ph.No' => '123321', 'Address' => 'Mascot', 'Name' => 'Sam' };

    Note though that I added a chomp (most of your values would otherwise have a trailing new line), limited split to finding two elements to avoid chopping off the end of any value that happens to contain a colon and check to see that there is in fact a value field on the line.


    True laziness is hard work
Re: Hash Add new elements through loop
by kiruthika.bkite (Scribe) on Mar 24, 2010 at 03:39 UTC
    use strict; use warnings; use Data::Dumper; my %record; while (<>) { if(/(.*):(.*)/) { $record{$1}=$2; } } print Dumper \%record;

    Input

    Name : Hari
    Ph.Num:123456
    Address :Mascot


    Output

    $VAR1 = {
    'Ph.Num' => '123456',
    'Address ' => 'Mascot',
    'Name ' => ' Hari'
    };