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

Is there a way to place text at a certain point in a string? For example, I need to write a script that will search through an html form and fill in the text fields with certain values.

I know I need to do something like the following:

if($string =~ /^<input type='text'/) { #place value="" attribute somewhere before the > }
Could someone please tell me how I could do this? Thanks.

Replies are listed 'Best First'.
Re: Pattern Matching and replacement
by tachyon (Chancellor) on Apr 14, 2003 at 02:16 UTC

    Actually you don't really want to do it that way. You do want to use something like WWW::Mechanize::FormFiller off CPAN which fills in forms and submits them for you. Ready to go at a CPAN mirror near you. You will also need to read the docs for WWW::Mechanize base class to see how you submit the result of the form you filled in with the FormFiller subclass. A few dozen lines of code then take the rest of the week off! Gotta love CPAN

    Modifying HTML with regexes is always a fragile solution. You need to use HTML::Parser if you want relaible parsing but as noted above all the hard work has been done for you already.....

    cheers

    tachyon

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

      You could also look at HTML::FillInForm which will do a similar task as what tachyon mentions above. And please take everyone's advice and don't use a regex for this...
Re: Pattern Matching and replacement
by dws (Chancellor) on Apr 14, 2003 at 02:42 UTC
    Is there a way to place text at a certain point in a string?

    substr(). One of the nifty aspects of Perl is that substr() can act as an LVALUE. That is, you can assign into it.

      perldoc -f substr for details.

Re: Pattern Matching and replacement
by The Mad Hatter (Priest) on Apr 14, 2003 at 02:18 UTC
    Usually writing regex's for HTML is a bad idea. In any case, you should be able to modify this to suit your needs.
    my $newvalue = "foobar"; foreach (<DATA>) { s/(<input .+? value=["']).*?(["'].*?>)/$1$newvalue$2/; print; } __DATA__ <input type="text" value=""> <input type="password" name="moo" value="fish" /> <input type="text" value=''/>
    Note that it assumes the tag already has a value attribute (either set or empty).
Re: Pattern Matching and replacement (tokeparser to the rescue)
by Aristotle (Chancellor) on Apr 14, 2003 at 10:53 UTC
    use strict; use warnings; use HTML::TokeParser::Simple; my $p = HTML::TokeParser::Simple->new("foo.html"); sub new_form_tag { my ($attr) = @_; $attr->{value} = "foo" if $attr->{name} eq "bar"; return join " ", "<input", map(qq($_="$attr->{$_}"), keys %$attr), + ">"; } while(my $token = $p->get_token) { print $token->is_start_tag('input') ? new_input_tag($token->return_attr) : $token->as_is; }
    The $attr->{value} = "foo" if $attr->{name} eq "bar" part can be as complex as desired, obviously.

    Makeshifts last the longest.