Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Incrementing Form inputs

by damian (Beadle)
on Jul 07, 2000 at 11:25 UTC ( [id://21418]=perlquestion: print w/replies, xml ) Need Help??

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

hi guys, i have this big project that accepts user inputs from an html form page. my problem is that i have 243 text inputs and my script is ovekilling with something like this. print FH "$FORM{item1}\t$FORM{qty1}\n" if $FORM{qty1}; print FH "$FORM{item2}\t$FORM{qty2}\n" if $FORM{qty2}; print FH "$FORM{item3}\t$FORM{qty3}\n" if $FORM{qty3}; up to .... print FH "$FORM{item243}\t$FORM{qty243}\n" if $FORM{qty243}; would you image what a waste of time coding 243 FORM inputs. is there a shortcut way for this like this one.... for ($i=1;$i<=243;$i++) { FH "$FORM{item$i++}\t$FORM{qty$i++}\n" if $FORM{qty$i++}; } but that won't work.... i am beginning to go balistic here.. help please.

Replies are listed 'Best First'.
Re: Incrementing Form inputs
by athomason (Curate) on Jul 07, 2000 at 11:46 UTC
    Hash keys are strings, so all you need to do is concatenate the 'item' or 'qty' with your index. The postincrements ('++') you have within the keys are redundant and will give you an error anyhow. So then we could clean your code up:
    for my $i ($i=1; $i<=243; $i++) { print FH "$FORM{'item' . $i}\t$FORM{'qty' . $i}\n" if $FORM{'qty' . $i}; }
    Though I'd be more likely use printf and an array slice for clarity in this case:
    for (1..243) { printf FH "%s\t%s\n", $FORM{"item${i}"}, $FORM{"qty${i}"} if $FORM{"qty${i}"}; }

    The braces aren't strictly necessary here, but will prevent confusion in the future if you need to append a static string after the interpolated variable.

Re: Incrementing Form inputs
by agoth (Chaplain) on Jul 07, 2000 at 15:59 UTC
    Or if youre happy using $_ why not :
    for (1..243) { print FH qq($FORM{"item$_"}\t$FORM{"qty$_"}\n) if $FORM{"qty$_"}; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-04-25 16:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found