http://qs321.pair.com?node_id=1126202


in reply to How to insert the content of a file into another file before/after a pattern match?

In File1 I see a pattern: the component blocks, architecture and signal declarations are separated by an empty line. Thus, the file is organized into paragraphs.

There is a command line switch for reading files in paragraph mode: -00 (see perlrun). The -n and -p switches construct an implicit loop around your code which does the read for you.

So, one way to achieve your goal (remember TIMTOWTDI - There Is More Than One Way To D It) would be something along the following:

#!/usr/bin/perl -n00 use strict; use warnings; our $snippet; BEGIN { my $snippetfile = shift; # first file on command line open my $fh, '<', $snippetfile or die "Can't read '$snippetfile': $!\n"; $snippet = <$fh>; # get entire block into $snippet close $fh or die "Can't close filehandle of '$snippetfile' properl +y: $!\n"; } if (/architecture/s) { print; # print current block print $snippet; # print snippet from file 1 } elsif (/signal/s) { print $snippet; # print snippet first print; # then the current block } else { print; }

Code is untested. Note that the second file containing the snippet comes first on the command line.
See perlmod for information about the BEGIN block. See perlfunc and perlop for open, close, my, our, shift, print and // (or m//) along with its modifiers, see also perlre.
Please read the docs. Please read the docs!

Doing the same using the implicit print of the -p switch is left as an exercise to the reader.

perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
  • Comment on Re: How to insert the content of a file into another file before/after a pattern match?
  • Select or Download Code