Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??


I often need to do small and incomplete parsers. An example of such parser is included at the and.

The principles of this parser

Read the file into $text. Divide $text in parts. The parts are represented in @part. For each part there is [ $type, $first, $last ]. $first and $last are positions in $text.

The parsing is done by the sub parse. It is controlled by @spec, which contains a number of [ $reg_exp, $type ]. All the $reg_exp start with \G. The $reg_exp are tried in order. After a match the tries starts with the first $reg_exp. The last $reg_exp must match so much that one of the other $reg_exp can match and the $type = '??'.

In this and in many cases the parsing is done step-by-step. In the example the first step is locating strings ( 'sq' and 'dq' ) and comments ( 'cn' and 'cb' ). The second step is then, in the parts with $type eq '??', locating names ( 'na' ), digits ( 'di' ) and reserved words ( 'rw' ).


By using the function pos() in combination with the \G zero-width assertion you can control where the regexp engine starts. The sub parser can been simplified if it was possible to set the position where the regexp engine stops.

Are there any easy way, with the current Perl, to control where the engine should stop?

Or is it feasible to add a new feature to Perl. Possibilities could be:

  • A new function stop_pos().
  • Extend the binary operator =~, which binds a scalar expression to a pattern match, with parameters like =~[$start, $stop].
  • Add a string slice $string.slice( $start, $stop), which can be used together with =~.
  • Let function substr return a lvalue which could be store in a (new type of?) scalar. The lvalue can then be used together with =~.

Example of parser

#!/usr/bin/perl -w use strict; use warnings; sub parse { my ( $txt_ref, $part_aref, $spec_aref ) = @_; my ( $type, $first, $last ); # for the current part # used in the current matching my $cur_txt_ref; my $cur_sub_str; my $cur_pos0; # start of $cur_sub_str in $$txt_r +ef my @part; # result from the parsing my $do_part = sub { my $end_last_match = 0; MATCH: { for my $spec (@$spec_aref) { my ( $reg_exp, $type ) = @$spec; if ( $$cur_txt_ref =~ m{$reg_exp}gcm ) { push @part, [ $type, $-[0] + $cur_pos0, $+[0] + $c +ur_pos0 ]; $end_last_match = $+[0]; redo MATCH; } } last MATCH; } if ( $end_last_match < length $$cur_txt_ref ) { warn 'ERROR: Stopped before string end at pos: ', "$cur_pos0 + $end_last_match\n<", substr( $$cur_txt_ref, $end_last_match ), '>'; } }; if ( not defined $part_aref ) { # use the whole $$txt_ref $cur_txt_ref = $txt_ref; $cur_pos0 = 0; $do_part->(); return \@part; } $cur_txt_ref = \$cur_sub_str; # use a substring from $$txt_re +f map { ( $type, $first, $last ) = @$_; if ( $type eq '??' ) { $cur_sub_str = substr( $$txt_ref, $first, $last - $first ) +; $cur_pos0 = $first; $do_part->(); } else { push @part, $_; } } @$part_aref; return \@part; } my @spec_1 = ( [ qr{\G'[^'\\]*(?:\\.[^'\\]*)*'}, 'sq' ], [ qr{\G"[^"\\]*(?:\\.[^"\\]*)*"}, 'dq' ], [ qr{\G//[^\n]*[\n]?}, 'cn' ], [ qr{\G/[*](?:[^*]*|[*]+[^/*]*)*[*]/}, 'cb' ], [ qr{\G(?:[^'"/]+|[/][^'"/*])+}, '??' ], ); my $dig1 = qr{-?\d+\.\d*}; my $dig2 = qr{-?\d*\.\d+}; my $dig3 = qr{-?\d+}; my $dig4 = qr{E-?\d+}; my $digit = qr{(?:$dig1|$dig2|$dig3)$dig4?}; my @spec_2 = ( [ qr{\G(?:var|alert)}, 'rw' ], [ qr{\G$digit}, 'di' ], [ qr{\G[_a-zA-Z0-9.\$]+}, 'na' ], [ qr{\G(?:[^_a-zA-Z0-9.\$\d]+|[\n\s]+)+}, '??' ], ); sub to_string_part_aref { my ( $txt_ref, $part_aref ) = @_; return join '', map { my ( $type, $first, $last ) = @$_; if ( $type eq '??' ) { substr( $$txt_ref, $first, $last - $first ); } else { "<$type>" . substr( $$txt_ref, $first, $last - $first ) . "</$type>"; } } @{$part_aref}; } my $text = do { local $/; <DATA> }; my $text_ref = \$text; my $part_ref_1 = parse( $text_ref, undef, \@spec_1 ); my $part_ref_2 = parse( $text_ref, $part_ref_1, \@spec_2 ); warn to_string_part_aref( $text_ref, $part_ref_2 ); exit 0; __DATA__ // This is a single-line comment var x = 4; // Single /* Multiple-line comment that can span any number of lines */ /* This is a multi-line comment // Still a multi-line comment */ /* Stop code var x = 4; var y = 5; /* Bug? * x = "cool"; End Stop code */ // This is a single-line comment /* ...still a single-line comment 'string\' // still a string'; // comment /* not-a-nested-comment var = 0.5; // comment */* still-a-comment ' /**/ string ' /* "comment..." // still-a-comment */ alert('This isn\'t a comment!'); /\/* this isn't a comment! */; //* comment /* //a comment... // still-a-comment 12345 "Foo /bar/ "" */ /*//Boo*/ /*/**/

In reply to Setting end position for the regexp engine by bojinlund

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    [Corion]: marto: You mean "Sane Dots Dramatic Reading of ITIL" ? ;)
    [marto]: Sane Dots, chapter 13: ITIL never work :P
    [marto]: sorry, bad pun of it'll :P
    [Corion]: :-D
    [Corion]: I think that ITIL is mostly to prevent people from doing harm to a system that basically runs unattended :)
    [Corion]: Maybe you could reduce ITIL to a computer network, a man and a dog. The network runs the computations. The man is there to feed the dog. The dog is there to prevent the man from accessing the computers.

    How do I use this? | Other CB clients
    Other Users?
    Others exploiting the Monastery: (12)
    As of 2017-01-24 10:28 GMT
    Find Nodes?
      Voting Booth?
      Do you watch meteor showers?

      Results (203 votes). Check out past polls.