0

I have 2 RegExps. How can I get the start position of first RegExp matched substring and start to find second RegExp matching from this position?

UPD: For example:

$_ = "
=cut
vffdv
vdfvfd
vdfvfdvfd
=pod
dvfddv
vfdvfdvf
vdfvfdvfd
=end
";
$\ = "\n";

sub get {
 my $_ = shift;
 /=((\d|\w)+)/i;
 return $1;
}


print get($_) while /^=/mg;

Prints

cut
cut
cut

But I need

cut
pod
end
michaeluskov
  • 1,729
  • 7
  • 27
  • 53

3 Answers3

3

You're sending $_ which doesn't change in while loop and it is defined at start of the script to get() function.

You need to capture content and send $1 to function.

print get($1) while /^=(.+)/mg;

Side note; most of the time do prefer named variables over implicit $_. Also my $_ = .. is asking for trouble if you're expecting dynamic scoping for $_ global, and lexical $_ is clobbering it.

mpapec
  • 50,217
  • 8
  • 67
  • 127
1

you can use something like this

$_ = "
=cut
vffdv
vdfvfd
vdfvfdvfd
=pod
dvfddv
vfdvfdvf
vdfvfdvfd
=end
";

my @array = split /\n/ , $_;
for ( @array ){
    if( $_ =~ /^=/ ){
        print substr( $_ , 1 ) . "\n";
    }
}
brianadams
  • 233
  • 1
  • 5
0

This works like I need.

$_ = "
=cut
vffdv
vdfvfd
vdfvfdvfd
=pod
dvfddv
vfdvfdvf
vdfvfdvfd
=fuck
";
$\ = "\n";

sub get {
 my $_ = shift;
 my $start = shift;
 pos($_) = $start - 1;
 /=((\d|\w)+)/ig;
 return $1;
}


print get($_,pos $_) while /^=/mg;
michaeluskov
  • 1,729
  • 7
  • 27
  • 53