Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

How do I pass values entered in the textfield into a hash?

by ltran (Initiate)
on Jul 03, 2001 at 13:07 UTC ( [id://93443]=perlquestion: print w/replies, xml ) Need Help??

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

How would I pass the values entered in the textfield into a hash as parameters i.e. people would enter something like this in the textfield;
1=>4, 3=>8
and I would like to pass these as key-value pairs into a hash. How would I do it?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: how do i pass values entered in the textfield into a hash ?
by davorg (Chancellor) on Jul 03, 2001 at 13:16 UTC

    Assuming that you've already used CGI.pm and declared the hash. And also that the text field is called hashdata...

    foreach (split /,\s*/, param('hashdata')) { my ($k, $v) = split(/=>/); $hash{$k} = $v; }

    If you know the hash is going to be empty at the start, then it gets a bit simpler...

    %hash = map { split /=>/ } split /,\s*/, param('hashdata');
Re: how do i pass values entered in the textfield into a hash ?
by tachyon (Chancellor) on Jul 03, 2001 at 21:12 UTC

    You might also want to add a little data filtration on the keys and values to at least strip leading and trailing whitespace otherwise "a=>4" will generate a different key to say " a =>4". Something like:

    foreach (split /,\s*/, param('hashdata')) { my ($k, $v) = split(/=>/); whitespace(\$k,\$v); $hash{$k} = $v; } sub whitespace { while (my $ref = shift){ $$ref =~ s/^\s+|\s+$//g } }

    We pass the sub references to the variables so we can change them in the sub and not bother having to return the changed values and assign them.

    cheers

    tachyon

      chromatic points out that split(/\s*=>\s*/) is is a shorter and more efficient solution to the whitespace problem:

      foreach (split /,\s*/, param('hashdata')) { my ($k, $v) = split(/\s*=>\s*/); $hash{$k} = $v; }

      I have to agree :-(

      cheers

      tachyon

      s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://93443]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (4)
As of 2024-03-29 00:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found