Convert String Hash

[problem]

Need to convert a string to a hash in Perl.

[/problem]

[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.

[/solution]

[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

[/example]

[reference]

[tags]Perl Coding School[/tags]

[/reference]

If you have found my website useful, please consider buying me a coffee below 😉

Leave a Reply

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