Tuesday, 10 January 2017

Exploring Here Documents in Perl

I find here documents as a very useful & interesting aspect of working with I/O.
A here document essentially allows us to feed static input arguments to an otherwise interactive program.

Here is a common example of using here documents with the cat command.

[ssuri@:~] $ cat > abc << EOF
> this is a
> a
> test file
> EOF
[ssuri@:~] $ cat abc
this is a
a
test file
[ssuri@:~] $

The syntax is the command followed by the << symbol & the limit string.
The limit string is used twice. Once before the << symbol & again at the end of input to infer that there is no further input to be entered beyond this point.


In this article I'd like to demonstrate using here documents in perl. I'll explore the concept using a simple script which will use the content generated by a here document assinged to a variable, copy it to a file & also print the content.
Here is the script.

#!/usr/bin/perl -w

use Fcntl;

open (FH1, "+> /tmp/afile") || die ;

my $heredoc = <<'END_MESSAGE' ;
server1
server2
server3
server4
server5
END_MESSAGE


print FH1 $heredoc ;

seek FH1, 0, 0;

my @herearray = <FH1> ;

foreach (@herearray) { print "this is server number $_ \n" ; }
[root@cent6 ~]#


In the above script we've used a here document to populate a variable named $heredoc. We then copy the contents of the variable to a file via the file hande FH1.
We then use the seek function to rewind or re-read the file afile via file handle FH1, assign it to an array & print it's contents.

The script when executed gives the following output.

[root@cent6 ~]# ./here.pl
this is server number server1

this is server number server2

this is server number server3

this is server number server4

this is server number server5


This is more of a proof of concept example.
We can use here documents for more advanced scripting.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...