Re: Load hash from a scalar



sanket vaidya wrote:

From: scooter [mailto:verma.abhinav@xxxxxxxxx]

I want to load the value from scalar variable to a hash

Example:
my $a = "a, 1, b, 2, c, 3";

Now, I need to create a hash %b, which holds values like
%b = { a => 1, b => 2, c => 3 };

Here is the code to accomplish your task.


use warnings;
use strict;

my $a = "a, 1, b, 2, c, 3";

$a =~ s/ //g; #delete spaces from $a

You can do that more efficiently with tr///:

$a =~ tr/ //d; #delete spaces from $a


my @array = split(",",$a);

Or you can delete the spaces when you split the string:

my @array = split / *, */, $a;


my %b = (
$array[0] => $array[1],
$array[2] => $array[3],
$array[4] => $array[5]
);

You can just assign a list directly to a hash:

my %b = @array;

Or just assign the list returned from split:

my %b = split / *, */, $a;


for (keys%b)
{
print "$_ => $b{$_}\n";
}

The output is:

c => 3
a => 1
b => 2


John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
.



Relevant Pages

  • Re: My hash table is in need of peer review
    ... may be worthwhile to cache the hash value. ... I define the load factor as the number of entries divided by ... At lower load factors (short linked lists) it was ... and where a string comparison can be ...
    (comp.lang.c)
  • Re: My hash table is in need of peer review
    ... may be worthwhile to cache the hash value. ... I define the load factor as the number of entries divided by ... At lower load factors (short linked lists) it was ... factor and thus the length of any chains involved, ...
    (comp.lang.c)
  • Re: My hash table is in need of peer review
    ... may be worthwhile to cache the hash value. ... I define the load factor as the number of entries divided by ... At lower load factors (short linked lists) it was ... and where a string comparison can be ...
    (comp.lang.c)
  • Re: my paper: A cascade hash algorithm with O(1) worst case lookup time
    ... Is there an upper-bound to the space needed to hold a cascade hash ... How does the average case compare with a linear probing ... assumes that the previous space will run at 50% load -- but that would ... undue load on the system's memory cache hierarchy then it may perform ...
    (comp.programming)
  • Re: large directory handling
    ... > #open directory and load contents into hash ... > use strict; ...
    (perl.beginners)