Convert String Hash

Problem

Need to convert a string to a hash in Perl.



Solution

Split can also be used to generate a hash, from a string.

In this instance split looks at two things, the key to value separator (in this case an equals sign) and the comma to separate groups.



Example



$str="mouse=one,cat=two,dog=three";
%ash=split /,|=/, $str;

while(($k,$v)=each(%ash)) {
print $k."=>".$v."n";
}

Produces:

cat=>two
dog=>three
mouse=>one



Reference

[tags]Perl Coding School[/tags]



Previous Post

Leave a Reply

Your email address will not be published. Required fields are marked *