I had a quick-and-dirty script that worked with the substring function as long as the offset and length of text were the same. This is no longer true. Now the length of text to be extracted is variable (and sometimes contains spaces).

I can determine the text around the substring. Let's say start and end.

I thought I could more generically extract the substring with split /start($_)end/ but I can't get the syntax right and it won't compile.

Here's the original script. It works, finding one $transactID and a dozen or so item/quantity instances in each file, but it's inflexible:

#!/usr/bin/perl -w use strict; use warnings; my $transactID = "item=" ; #### Usually a number my $itemname = "itemname" ; #### Usually alphanumeric my $quantity = "qty" ; #### Always numeric open(IN,'ItemsFile.rtf') or die("can't open input file\n"); open(OUT,'>results.txt') or die("can't open output file\n"); while(<IN>){ print OUT "0 ", substr($',3,17), "; " if($_ =~/\b$transactID\b/i); print OUT "1 ", substr($',2,12), "; " if($_ =~/\b$itemID\b/i); print OUT "2 ", substr($',13,3), "; " if($_ =~/\b$quantity\b/i); + } close(IN); close(OUT);

Note that start sometimes contains spaces.


In reply to Extracting variable-length strings between delimiters by PMReader

Title:
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, details, 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, summary, 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.