Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: printing LAST_MATCH_START/@- LAST_MATCH_END/@+ array where regex match begin/end

by choroba (Archbishop)
on Dec 26, 2021 at 21:26 UTC ( #11139918=note: print w/replies, xml ) Need Help??


in reply to printing LAST_MATCH_START/@- LAST_MATCH_END/@+ array where regex match begin/end

Move the match with /g into a condition of a while loop.

As there are no capture groups in the regex (i.e. no parentheses), using any other index than 0 makes no sense. Under warnings, you'd even get lots of Use of uninitialized value in print.

Moreover, when there's no match, the @- and @+ arrays are empty, there's no -1 (that's what index does). You have to handle that case yourself.

This should work directly as shown and output the expected output:

#!/usr/bin/perl use strict; use warnings; my $string = << "__EOS__"; foo bar baz foo bar foo\tbaz ccc ddd foo bar foo\tbaz ccc ddd\tfoo\tbar\tbaz foo bar foo\t\tbaz ccc ddd\t\t\tfoo __EOS__ open my $F0, '<', \$string or die $!; while (<$F0>) { my $match; while (/\t+/g) { $match = 1; print $-[0], ' ', $+[0], ' '; } print '-1 -1' unless $match; print "\n"; }

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: printing LAST_MATCH_START/@- LAST_MATCH_END/@+ array where regex match begin/end
by perl_boy (Novice) on Dec 29, 2021 at 00:57 UTC
    thank's for the tip. I have replaced the code inside the while loop with code you provided
    open(F0, $ARGV[0]); while(<F0>) { my $match; while (/\t+/g) { $match = 1; print $-[0], ' ', $+[0], ' '; } print '-1 -1' unless $match; print "\n"; } close F0;
    and works fine and get the expected results. good thank's :)))

    However I find that that PerlDoc https://perldoc.perl.org/perlvar#Variables-related-to-regular-expressions
    is a bit misleading when it says that indexes/positions before and after regex match can be found in the LAST_MATCH_START/@- and LAST_MATCH_END/@+ array by printing
    print $+[0], " ",$+[1], " ", $+[2], "\n" ;

    again thank's for the code :)))

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2022-05-25 06:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (84 votes). Check out past polls.

    Notices?