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

I am developing a script that uses WWW::Mechanize. Some users will have more or less HTML form fields than others, so my script has to accomodate for that.

I have variables like this for data

$var1_a = "name"; $var1_b = "Richard"; $var2_a = "age"; $var2_b = "12"; $var3_a = "location"; $var3_b = "mars";
Now some of these vars will NOT be used and will be set to ="". A's are the field names, B's are the values.

Is there a better way to set this up? Preferably a way that the user can add INFINITE form fields for WWW::Mechanize to pull through?

Other question is a two parter. If using MY method of hard coding the vars, how do I transfer them to my $mech call the most efficient way? I don't suppose I can put if conditionals in the FIELDS() to see whether certain fields were used.

$mech->submit_form( form_name => $search_form, fields => { $forum_user => $username, $forum_pass => $password, } );
2nd question is, if you have a better way of storing the data and looping over the form fields/values, can you post an example?

Replies are listed 'Best First'.
Re: WWW::Mechanize with optional fields
by Joost (Canon) on Jun 24, 2006 at 10:44 UTC
Re: WWW::Mechanize with optional fields
by shmem (Chancellor) on Jun 24, 2006 at 10:43 UTC
    Given that each form field name must be unique in a form just use a hash reference:
    my @names = qw(name age location); # add do this list whenever # make a hash reference and populate it @$fields{@names} = ( ... list of corresponding values ...);
    This expression may seem obscure, I'll explain it a bit. Consider:
    # a normal hash assignment - scalar context $field{'name'} = 'Richard'; # a normal hash assignment - list context @field{qw(name age)} = qw(Richard 24);
    So, @$fields{@names} does this:
    • using {} in the lvalue perl is told it's a hash, the {} takes keys
    • the @ tells perl $fields is a reference, dereferences it and uses it in list context
    • now you can assign it a list.
    Using strict you must declare the symbol $fields before accessing it:
    use strict; my @names = qw(name age location); # add do this list whenever # make a hash reference and populate it my $fields = {}; # declare $fields being a hash reference @$fields{@names} = ( ... list of corresponding values ...);
    That way you can pass the hash reference directly to submit_form:
    $mech->submit_form( form_name => $search_form, fields => $fields, } );
    The second question I cannot answer because I don't know how you do it...
    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}