wrml has asked for the wisdom of the Perl Monks concerning the following question:

So I have a script that replaces certain strings with other strings identified with a regex and a hash. I have the following problem: The way I have written the script, I break lines into substrings, do the substitution on one part but not the other, and then put them together. this works fine. The problem is, the last string in all these files is on character long... so short that when I try to cut in into substrings, there is a failure. It says:
substr outside of string at ReturnA/ReturnAReplacer.pl line 90, <IN> l +ine 8453.

the thing is, I don't care. I realize the last one is always too short, but I want it to go on and deal with the next file anyway. I can't tell it to just ignor the 8574th line because in the next file it might be the 19756th line and so one... forty some-odd files, each with a different number of lines.

Here's the code:

foreach $file (@infile){ open(IN, '<', "$file") or warn $! and next; open(OUT, '>', $outpath.basename($file)) or warn $! and next; while (<IN>) { substr($_,279) =~ s/$regex/$substitute{$1}/g; print OUT $_; } }

Replies are listed 'Best First'.
Re: substring too short and I don't care
by ikegami (Patriarch) on Aug 19, 2005 at 20:03 UTC
    Replace
    substr($_,279) =~ s/$regex/$substitute{$1}/g;
    with
    substr($_,279) =~ s/$regex/$substitute{$1}/g unless length < 279;
    or with
    { no warnings; substr($_,279) =~ s/$regex/$substitute{$1}/g; }
Re: substring too short and I don't care
by Fletch (Bishop) on Aug 19, 2005 at 20:05 UTC
    # . . . while( <IN> ) { if( length >= 279 ) { substr( $_, 279 ) =~ ... } print OUT $_; }

    --
    We're looking for people in ATL

Re: substring too short and I don't care
by Transient (Hermit) on Aug 19, 2005 at 20:03 UTC
    if ( length($_) > 279 ) { substr($_,279) =~ s/$regex/$substitute{$1}/g; print OUT $_; }
      That will silently discard any line with length < 279! I think you meant to print outside the if...
        Correct - I didn't read that the OP wanted to keep the line. The intent was to show how to get past the substr error, the skipping of the print statement was not intended to be of consequence.