Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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

by shmem (Chancellor)
on May 09, 2015 at 18:41 UTC ( [id://1126202]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1126202]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2025-06-23 22:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.