0

I have a variable my $html and it holds a string value. I want to cut it after the word

</SELECT>

How can I do that with Perl?

4 Answers 4

3
use warnings;
use strict;

my $html = '<SELECT>foo</SELECT> bar';
$html =~ s{(</SELECT>).*}{$1};
print "$html\n";

__END__

<SELECT>foo</SELECT>

You should also consider using one of the many HTML parsers on CPAN.

0
2
$html =~ s#</SELECT>.*$#</SELECT>#;

You can probably write it without the </SELECT> being in the replacement string, but IMHO it would be less readable.

Please note that s/// substitution can use other characters aside from / as separators, and in this case I chose to use # because your regular expression contains forward slash character that would otherwise have to be escaped making the regex less readable

2
  • If the $html string contains multiple lines, then the regexp above will only match </SELECT> if it is on the first line. You need to add the 's' modifier to treat the string as a single line. s#</SELECT>.*$#</SELECT>#s; Apr 13, 2011 at 21:26
  • @Sam - I'm not sure whether OP meant line-independent or not... if line independent. you are indeed correct.
    – DVK
    Apr 14, 2011 at 14:56
1

Don't use a regexp (power saw) when a knife (look for fixed string) is enough:

my $html = 'use dom to work with </SELECT> html!';
my $cut  = '</SELECT>';
printf "|%s|\n", substr( $html, index( $html, $cut ) + length( $cut ) );
==>
| html!|
0

If you want to get the text which stands before the first </SELECT> you could use a regex like this:

$html =~ /(.*?<\/SELECT>)/;
my $required_text = $1;

or in one step:

my ($required_text) = $html =~ /(.*?<\/SELECT>)/;

It uses the non-greedy modifier ? which I think is what you need.
Or better the substr() subroutine like the previous answer says.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.