(Niall Macpherson) wrote in
news: om:
> I am trying to find the first occurence of anything between a '[' and
> a ']' and return that string
In addition to the useful responses by others, consider reading the faq
entry
perldoc -q match
Also, for simple string matches, keep in mind the index function:
perldoc -f index
> use strict;
> use warnings;
> use diagnostics;
>
> sub GetString
> {
> my ($teststring) = @_;
>
> if ($teststring =~ /\[.*\]/)
> {
> my $match = $&;
Have you read perldoc perlvar?
$& The string matched by the last successful pattern match
....
The use of this variable anywhere in a program imposes a
considerable performance penalty on all regular expression
matches. See "BUGS".
If you wanted to do what you are doing above in a better way, you could
do this:
#! perl
use strict;
use warnings;
my $s = 'Hello [ insert planet name here ]';
print scalar find_bracketed_string($s), "\n";
sub find_bracketed_string {
my ($s) = @_;
my ($l, $r);
if(($l = 1 + index $s, '[') > $[
and ($r = index $s, ']', $l) >= $[) {
my $rs = substr $s, $l, $r - $l;
return wantarray ? ($rs, $r + 1) : $rs;
}
return;
}
Sinan.