in reply to Substitute Question

Okay, so this is a bit late. I'm just adding it because it's an obvious use of the range operator for extracting the data. Using some of the tomfoolery above but trying to match the specs as I understand them (no, not trying to golf):
use strict; use warnings; my $start_tag = qr/\*\*\* begin file \*\*\*/; my $end_tag = qr/\*\*\* end file \*\*\*/; my $case = ''; while ( <DATA> ) { # The range operator is sorely underused. if ( /$start_tag/ .. /$end_tag/ ) { if ( /$start_tag/ or /$end_tag/ ) { s/file/substituted file/; } else { $case = $_ & ' ' x length; s/old/NEW/i; } print $_ | $case; } } __DATA__ test *** begin file *** old_word OLD_WORD oLd_wOrd olD_worD *** end file *** test2
Prints:
*** begin substituted file *** new_word NEW_WORD nEw_wOrd neW_worD *** end substituted file ***

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: (Ovid - coming in late) Re: Substitute Question
by merlyn (Sage) on May 30, 2001 at 02:31 UTC
    You can replace:
    if ( /$start_tag/ .. /$end_tag/ ) { if ( /$start_tag/ or /$end_tag/ ) {
    with
    if ( my $where = /$start_tag/ .. /$end_tag/ ) { if ( $where == 1 or $where =~ /E/ ) {
    for more reliable (and faster!) operation.

    -- Randal L. Schwartz, Perl hacker

      Hey, that's sweet! If you want to get rid of another regex and make it even faster:

      if ( $where == 1 or substr($where, -2) eq 'E0' ) {

      Though I am wondering one thing: why is 'E0' appended to the return value of the final sequence number? Is it just an easy test for the end or is there something significant here that I'm not aware of? (i.e., why not just append an 'x' or 'mssux' or something like that?).

      Cheers,
      Ovid

      Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.