paulgorman.org/technical

Perl as a Glue Language

(August 2016)

Here’s a good header for our Perl files:

#!/usr/bin/env perl

use v5.10;
use strict;
use warnings;
use autodie;

Get command line arguments

say scalar @ARGV;    # The number of arguments.
say $ARGV[0];        # The first argument
say $0;              # The name of this script.

Reading a file line by line by line

my $filename = '/tmp/stuff.txt';
open my $fh, '<', $filename;
while (my $line = <$fh>) {
	chomp $line;
	say $line;
}

Slurp in an entire (not too large) file at once

my $filename = '/tmp/stuff.txt';
open my $fh, '<', $filename;
my $contents = do { local $/; <$fh> };

See an explanation at http://www.perlmonks.org/?node_id=287647. In short, the built-in $/ tells Perl where to stop reading; it’s set to newline by default. We undefine $/ in this block scope in order to continue reading until the end of file.

Check if a file exists

say "Found the plain file $file_path" if -f $file_path

There are other file tests besides -f. See:

$ perldoc -f '-X'

Write to a file

my $filename = '/tmp/stuff.txt';
open my $fh, '>', $filename;
print $fh "Here's a line of text\n";

To append rather than overwrite, open the filehandle with a double-carrot:

open my $fh, '>>', $filename;

Recurse through directory tree

use File::Find;

my @files;
my $root = "/home/paulgorman/tmp";
find(
	sub { push @files, $File::Find::name unless -d; },
	$root
);
for my $file (@files) {
	say $file;
}

All text files in a directory non-recursively

my @files = glob ('/home/paulgorman/tmp/*.class');
for my $file (@files) {
	say $file;
}
print STDERR "We dun messed up.\n";

Escape a string for the shell

Avoid the issue by using system():

use IPC::System::Simple qw(system);
system('command', 'arg1', 'arg2');

But if we must, look at String::ShellQuote.

Run a shell command

Get output of a shell command

Hook up to the shell’s standard handles

Spawn a new process, and don’t wait for it to exit

Fork a Copy and Communicate via Unix Sockets

Read from and Write to a Unix Named Pipe (FIFO)

Web serve the current directory

$ cpan HTTP::Server::Brick $ perl -MHTTP::Server::Brick -e
‘$s=HTTP::Server::Brick->new(port=>8000); $s->mount(“/”=>{path=>“.”}); $s->start’

Web serve a simple message

Fetch URL (GET)

Fetch URL (POST)

Die!