in reply to Modify a line following a target line?

If you can load the entire file into memory, the following will split the file into records:
my @records = split(/^(?=I)/m, $file);

The just extract the REFDES and modify the PKG_TYPE

my %pkg_lkup ( ... => ..., ... => ..., ... => ..., ); for my $rec (@records) { if ( my ($refdes) = $rec =~ /REFDES=(.*)/ ) { if (exists($pkg_lkup{$refdes})) { $rec =~ s/PKG_TYPE=.*/PKG_TYPE=$pkg_lkup{$refdes}/; } } print($rec); }

In Perl 5.10, the substitution can be written more efficiently as

$rec =~ s/PKG_TYPE=\K.*/$pkg_lkup{$refdes}/;

Replies are listed 'Best First'.
Re^2: Modify a line following a target line?
by djincnj (Initiate) on Jan 06, 2009 at 17:09 UTC
    OK I think I understand this all for the most part, I've been working on files on a line by line basis for so long I didn't think I could break it up any other way. But of course something I imagine is pretty simple has got me stuck.

    How do I get the entire content of a file into $file? I know how to read a file into @file, but I'm at a loss how to read the whole thing into $file to then split it up.

      The canonical solution is:

      my $file = do { local $/; <>; };

      But, we're in Perl, so there's more than one way to do it.

      $file = join( '', <> );

      also works. Of course, you could look at File::Slurp for a CPAN-based solution that's a little more readable.

      PS. if you have an open filehandle in $fh, you would replace <> with <$fh> in the above, of course.

      G. Wade