SlideShare a Scribd company logo
Visit https://ebookultra.com to download the full version and
explore more ebooks
Programming the Network with Perl 1st Edition
Paul Barry
_____ Click the link below to download _____
https://ebookultra.com/download/programming-the-
network-with-perl-1st-edition-paul-barry/
Explore and download more ebooks at ebookultra.com
Here are some suggested products you might be interested in.
Click the link to download
Graphics Programming with Perl 1st Edition Martien
Verbruggen
https://ebookultra.com/download/graphics-programming-with-perl-1st-
edition-martien-verbruggen/
Modern Perl Programming 1st Edition Michael Saltzman
https://ebookultra.com/download/modern-perl-programming-1st-edition-
michael-saltzman/
Beginning Programming with Java For Dummies 4th Edition
Barry Burd
https://ebookultra.com/download/beginning-programming-with-java-for-
dummies-4th-edition-barry-burd/
Beginning Programming with Java for Dummies 5th Edition
Barry Burd
https://ebookultra.com/download/beginning-programming-with-java-for-
dummies-5th-edition-barry-burd/
Advanced Perl Programming Second Edition Simon Cozens
https://ebookultra.com/download/advanced-perl-programming-second-
edition-simon-cozens/
Penetration Testing with Perl 1st Edition Berdeaux
https://ebookultra.com/download/penetration-testing-with-perl-1st-
edition-berdeaux/
HTML5 Programming with JavaScript For Dummies 1st Edition
John Paul Mueller
https://ebookultra.com/download/html5-programming-with-javascript-for-
dummies-1st-edition-john-paul-mueller/
Windows sockets network programming 1st Edition Bob Quinn
https://ebookultra.com/download/windows-sockets-network-
programming-1st-edition-bob-quinn/
Beginning Programming with Python For Dummies 3rd Edition
John Paul Mueller
https://ebookultra.com/download/beginning-programming-with-python-for-
dummies-3rd-edition-john-paul-mueller/
Programming the Network with Perl 1st Edition Paul Barry
Programming the Network with Perl 1st Edition Paul
Barry Digital Instant Download
Author(s): Paul Barry
ISBN(s): 9780471486701, 0471486701
Edition: 1
File Details: PDF, 1.18 MB
Language: english
Programming the Network with Perl 1st Edition Paul Barry
Programming the Network with Perl 1st Edition Paul Barry
Programming the Network with Perl 1st Edition Paul Barry
Programming the Network with Perl 1st Edition Paul Barry
Paul Barry
Institute of Technology, Carlow, Ireland
Copyright ©2002 John Wiley & Sons Ltd
Baffins Lane, Chichester,
West Sussex PO19 1UD, England
National 01243 779777
International (+44) 1243 779777
e-mail (for orders and customer service enquiries): cs-books@wiley.co.uk
Visit our Home Page on http://www.wileyeurope.com or http://www.wiley.com
All Rights Reserved. No part of this publication may be reproduced, stored in a retrieval
system, or transmitted, in any form or by any means, electronic, mechanical, photocopying,
recording, scanning or otherwise, except under the terms of the Copyright, Designs and
Patents Act 1988 or under the terms of a licence issued by the Copyright Licensing Agency
Ltd, 90 Tottenham Court Road, London, UK W1P 0LP, without the permission in writing of
the Publisher with the exception of any material supplied specifically for the purpose of
being entered and executed on a computer system for exclusive use by the purchaser of
the publication.
Neither the author nor John Wiley & Sons, Ltd accept any responsibility or liability for loss
or damage occasioned to any person or property through using the material, instructions,
methods or ideas contained herein, or acting or refraining from acting as a result of such
use. The author and publisher expressly disclaim all implied warranties, including mer-
chantability or fitness for any particular purpose. There will be no duty on the author or
publisher to correct any errors or defects in the software.
Designations used by companies to distinguish their products are often claimed as trade-
marks. In all instances where John Wiley & Sons, Ltd is aware of a claim, the product names
appear in capital or all capital letters. Readers, however, should contact the appropriate
companies for more complete information regarding trademarks and registration
Library of Congress Cataloging-in-Publication Data
(applied for)
British Library Cataloguing in Publication Data
A catalogue record for this book is available from the British Library
ISBN 0 471 48670 1
Typeset in 9.5/12.5pt Lucida Bright by T&T Productions Ltd, London.
Printed and bound in Great Britain by Biddles Ltd, Guildford and Kings Lynn.
This book is printed on acid-free paper responsibly manufactured from sustainable
forestry in which at least two trees are planted for each one used for paper production.
Dedicated to Deirdre,
for continuing to put her ambitions on hold
while I pursue mine.
Programming the Network with Perl 1st Edition Paul Barry
Contents
Preface xiii
1 Meet Perl 1
1.1 Perl’s Default Behaviour 1
1.1.1 Our first Perl program 2
1.1.2 Perl’s default variable 3
1.1.3 The strange first line explained 3
1.2 Using Variables in Perl 4
1.2.1 One of something: scalars 5
1.2.2 A collection of somethings: arrays and lists 6
1.2.3 Hashes 8
1.2.4 References 9
1.2.5 Built-in variables 12
1.2.6 Scoping with local, my and our 12
1.3 Controlling Flow 13
1.3.1 if 13
1.3.2 The ternary conditional operator 14
1.3.3 while 15
1.3.4 for 15
1.3.5 unless 16
1.3.6 until 16
1.3.7 foreach 16
1.3.8 do 17
1.3.9 eval 17
1.3.10 Statement modifiers 18
1.4 Boolean in Perl 19
1.5 Perl Operators 20
1.6 Subroutines 21
1.6.1 Processing parameters 21
1.6.2 Returning results 22
1.6.3 I want an array 23
1.6.4 In-built subroutines 23
1.6.5 References to subroutines 26
1.7 Perl I/O 26
1.7.1 Variable interpolation 28
1.8 Packages, Modules and Objects 29
1.8.1 Modules 30
1.8.2 Objects 30
1.8.3 The joy of CPAN 31
1.9 More Perl 32
1.10 Where To From Here? 32
viii Contents
1.11 Print Resources 32
1.12 Web Resources 33
2 Snooping 35
2.1 Thank You, Tim Potter 36
2.2 Preparing To Snoop 37
2.2.1 Installing NetPacket::* 37
2.2.2 Installing Net::Pcap 38
2.2.3 Installing Net::PcapUtils 39
2.2.4 Online documentation 39
2.2.5 Configuring your network interface 40
2.3 Building Low-Level Snooping Tools 41
2.3.1 loop = open + next 42
2.3.2 Optional parameters: loop and open 43
2.3.3 Optional parameters: the callback function 45
2.3.4 Ethernet Analysis 45
2.3.5 EtherSnooper (v0.01) 48
2.3.6 EtherSnooper (v0.02) 52
2.3.7 EtherSnooper (v0.03) 55
2.3.8 Displaying IP addresses 58
2.4 Snooping IP Datagrams 63
2.4.1 EtherSnooper (v0.05) 64
2.4.2 EtherSnooper (v0.06) 67
2.5 Transport Snoopers 69
2.5.1 Preparing to snoop UDP 70
2.5.2 Preparing to snoop TCP 70
2.5.3 The TCP and UDP gotcha! 71
2.5.4 Application traffic monitoring 75
2.5.5 EtherSnooper (v0.07) 81
2.6 The Network Debugger 83
2.6.1 Processing command-line parameters 85
2.6.2 Storing captured results 85
2.6.3 The NetDebug source code 86
2.7 Where To From Here? 95
2.8 Print Resources 95
2.9 Web Resources 96
3 Sockets 99
3.1 Clients and Servers 99
3.1.1 Client characteristics 100
3.1.2 Server characteristics 101
3.2 Transport Services 101
3.2.1 Unreliable transport 102
3.2.2 Reliable transport 103
3.3 Introducing the Perl Socket API 104
3.4 Socket Support Subroutines 105
3.4.1 inet_aton and inet_ntoa 105
3.4.2 Socket addresses 105
3.4.3 getservbyname and getservbyport 106
3.4.4 getprotobyname and getprotobynumber 106
3.4.5 gethostbyname and gethostbyaddr 107
3.5 Simple UDP Clients and Servers 108
3.5.1 Testing with localhost 108
3.5.2 The first UDP server 108
3.5.3 The first UDP client 111
Contents ix
3.6 Genericity and Robustness 112
3.7 UDP Is Unreliable 116
3.7.1 No flow control 117
3.8 Sending and Receiving with UDP 118
3.9 Dealing with Deadlock 120
3.9.1 Specifying a time-out 121
3.9.2 Checking for data 123
3.9.3 Spawning a subprocess 125
3.10 TCP Clients and Servers 130
3.10.1 The first TCP server 131
3.10.2 The first TCP client 134
3.11 A Common TCP Gotcha 140
3.12 More TCP Socket Communication 143
3.12.1 The remote syntax checker server 144
3.12.2 The remote syntax checker client 147
3.13 The Concurrent Syntax Checker 150
3.14 Object-Oriented Sockets 153
3.14.1 IO::Socket 154
3.14.2 IO::Socket::INET 154
3.14.3 An object-oriented client and server 156
3.15 Where To From Here? 158
3.16 Print Resources 158
3.17 Web Resources 159
4 Protocols 161
4.1 Gotcha! 161
4.1.1 What’s the deal with newline? 162
4.2 Working with the Web 164
4.2.1 HTTP requests and responses 164
4.3 The World’s Worst Web Browser 165
4.3.1 Embedded graphics 168
4.3.2 A persistent wwwb 169
4.3.3 A better get_resource 172
4.4 HTTP Status Codes 174
4.5 It’s the Gisle and Graham Show! 178
4.5.1 Getting libwww-perl and libnet 179
4.6 The Library for WWW Access in Perl 180
4.6.1 The libwww-perl classes 181
4.7 The LWPwwwb Program 181
4.8 Doing More with LWPwwwb 184
4.8.1 Parsing HTML 185
4.8.2 Some parsewwwb examples 187
4.8.3 The HTML::Parser examples 189
4.9 Building a Custom Web Server 190
4.9.1 The custom Web server source code 190
4.9.2 The custom Web server in action 196
4.10 The libnet Library 197
4.10.1 Working with Usenet 198
4.10.2 The news reading source code 199
4.11 Email Enabling simplehttpd 205
4.11.1 The simple mail transfer protocol 205
4.11.2 The Net::SMTP module 210
4.11.3 Creating simplehttp2d 211
x Contents
4.12 Other Networking Add-On Modules 213
4.12.1 Installing Net::Telnet 213
4.12.2 A Net::Telnet example 214
4.13 Where To From Here? 217
4.14 Print Resources 217
4.15 Web Resources 217
5 Management 221
5.1 Simple Management with ICMP 222
5.2 Doing the Ping Thing 222
5.2.1 Some ping examples 223
5.3 Doing the Net::Ping Thing 225
5.4 Tracing Routes 227
5.4.1 How traceroute works 228
5.5 Not So Simple Management with SNMP 229
5.5.1 A little SNMP history 229
5.6 The SNMP Management Framework 230
5.7 Managed Data 231
5.7.1 The TCP/IP MIB 231
5.8 The SNMP Protocol 235
5.8.1 SNMP’s operational model 235
5.8.2 A brief tour of SNMPv1, SNMPv2 and SNMPv3 235
5.8.3 SNMP communities 237
5.9 The Net::SNMP Module 237
5.9.1 The Net::SNMP methods 238
5.10 Working With Net::SNMP 240
5.10.1 Working with mnemonic object identifiers 242
5.10.2 The udpstats source code 243
5.10.3 The howlongup program 247
5.11 What’s Up? 249
5.11.1 Being more careful 254
5.12 Setting MIB-II Data 256
5.13 IP Router Mapping 258
5.14 Where To From Here? 266
5.15 Print Resources 266
5.16 Web Resources 267
6 Mobile Agents 269
6.1 What is a Mobile Agent? 269
6.1.1 Mobile agent = code + state 270
6.1.2 What is a mobile-agent environment? 270
6.2 Mobile-Agent Examples 270
6.2.1 Revisiting multiwho 270
6.2.2 Revisiting ipdetermine 271
6.3 Mobile-Agent Advantages/Disadvantages 272
6.4 Perl Agents 274
6.4.1 Preparing Perl for mobile agents 274
6.5 The Agent.pm Module 275
6.6 Ooooh, Objects! 276
6.7 The Default Mobile Agent 276
6.8 A Launching Mobile-Agent Environment 280
6.9 A One-Shot Location 282
Contents xi
6.10 Relocating To Multiple Locations 284
6.10.1 Processing multiple mobile agents 285
6.10.2 Identifying multiple locations 285
6.10.3 A multi-location mobile agent 287
6.11 The Mobile-Agent multiwho 292
6.12 The Mobile-Agent ipdetermine 293
6.13 The Cloning Mobile-Agent ipdetermine 297
6.14 Other Perl Agent Examples 304
6.15 Where To From Here? 305
6.16 Print Resources 305
6.17 Web Resources 305
Appendix A. Essential Linux Commands 307
Appendix B. vi Quick Reference 311
Appendix C. Network Employed 315
Appendix D. Sample NetDebug Results 317
Appendix E. The OIDs.pm Module 363
Index 369
Programming the Network with Perl 1st Edition Paul Barry
Preface
The study of Computer Networking, long considered an adjunct to traditional
third-level computing programmes, has moved into the mainstream. The Insti-
tute of Technology, Carlow, where I lecture, was the first third-level college in
Ireland to develop an advanced four-year degree programme devoted entirely to
the study of Computer Networking. Students learn computing from a networking
perspective, and are trained in traditional programming technologies such as C,
C++ and Java. In addition, the established degree programmes have been peri-
odically reviewed to include new mainstream technologies, with recent emphasis
on including the technologies associated with computer networks, concentrating,
from a programming perspective, on network sockets.
Using a traditional programming language to program network sockets (and
networks in general) is a well-established practice. Unfortunately, some students
have difficulty grasping the details of these languages, and, consequently, struggle
with the complexities of programming network sockets. However, when a higher-
level language like Perl is used, students are more comfortable with it and enjoy
greater programming success.
Of course, there is more to programming the network than programming net-
work sockets. The modern network programmer needs to be able to analyse the
network traffic programs generate, interact with standard network protocols, and
manage complex networked systems.
What is in this book
This book supports the study of computer networking through the medium of
Perl programming.
Following an introduction to Perl (in Chapter 1, Meet Perl), the focus is on debug-
ging. Programmers know how to debug programs. When it comes to the network,
they need to know how to debug communications. In Chapter 2, Snooping, some
simple Perl programs are built to capture and analyse the traffic network applica-
tions generate. In the absence of any custom network applications, these simple
programs are used to analyse the traffic generated by some standard network
technologies.
xiv Preface
With the analysis tools in place, Chapter 3, Sockets, details the creation of a col-
lection of custom network applications using the Socket application programmer
interface. These are then developed to add increasing levels of sophistication.
The experience of building networked applications is good preparation for
interaction with the standard protocols of the Internet, the biggest computer net-
work of all. In Chapter 4, Protocols, the standard and add-on facilities of Perl are
used to interact with a selection of standard protocols and applications.
It is important to build robust custom network applications. It is also important
to be able to manage the networked environment within which these applications
operate. The Internet provides a standard mechanism to do this, and Perl is used
to program it in Chapter 5, Management.
Programming the Network with Perl concludes with Chapter 6, Mobile Agents,
which explores an area of computer networking that is generating considerable
research. Many believe Mobile-Agent Technology to be one of the ‘next big things’
on the Internet.
At the end of each chapter, a list of Print and Web Resources is provided to facil-
itate further study. All chapters conclude with a set of programming exercises.
Who should read this book?
Programming the Network with Perl evolved from my involvement in teaching
a 30 week computer networking module to a group of final-year undergradu-
ate software engineers. The material presented here is derived from the practical
material developed for the course. Since there is a high practical content related to
the study of computer networking, Programming the Network with Perl is highly
complementary to such a course. In addition, any course on programming Perl
will benefit from the real-world examples illustrated. The professional Perl pro-
grammer should also find the material interesting, as it is no longer enough to
program the computer – the modern programmer needs to know how to program
the network.
Platform notes
The Linux platform provides a host for our work. Not only is Linux a modern,
feature-rich operating system, it is also available free of charge, and is, therefore,
readily available. Linux provides excellent support to the Perl programmer. All the
code in Programming the Network with Perl should run unaltered on any Linux
platform, regardless of the underlying hardware technology. Users of UNIX or
BSD derived systems should experience no real problems running the code. When
working on Windows or Mac OS (prior to release X), getting the code in Chapter 2
to work will cause the most difficulty, although most of the code in the other
chapters should run unaltered on these non-UNIX operating systems. For readers
new to Linux, two appendixes provide quick references to the most frequently
used Linux commands and to the vi text editor.
Preface xv
The network used during the development of Programming the Network with
Perl is built from Ethernet hardware and TCP/IP software. The Ethernet network
is connected to the global Internet via a cisco router and an ATM connection. The
Network Employed appendix provides additional details on the network used (see
the diagram on p. 316).
Unless otherwise stated, use of at least release 5.6.0 of the Perl programming
language is assumed.
Accompanying website
Details of the mailing-list, source code, errata and other material related to Pro-
gramming the Network with Perl can be found on the book’s website, located at
http://glasnost.itcarlow.ie/˜pnb/index.html.
Your comments are welcome
I welcome all comments (good and bad) about Programming the Network with
Perl. Contact me via email at paul.barry@itcarlow.ie. Alternatively, write to
me care of the publisher.
Acknowledgments
Thanks to Mark T. Sebastian for providing a detailed technical review of the
manuscript, and to Greg McCarroll for his constructive criticism. My father, Jim
Barry, thoroughly proof-read the entire manuscript and suggested many improve-
ments to my writing style. A big thank-you to the team (Robert Hambrook, Jill
Jeffries and Karen Mosman) at John Wiley & Sons, Ltd. Thanks to Michael Baker,
John Hegarty, Austin Kinsella and Colm O’Connor at The Institute of Technology,
Carlow. Thanks, too, to the students of CW082-4 for helping to debug many of the
example programs. And hats off to Sam Clark (of T&T Productions Ltd) for turning
my amateur L
A
TEX into that which you see before you now.
I would like to acknowledge a small group of inventors for their inventions:
Linus Torvalds for Linux, Bill Joy for vi, Leslie Lamport for L
A
TEX and, of course,
Larry Wall for Perl. This book was inspired by the last invention, and produced
with the first three.
Programming the Network with Perl would never have been written without the
continued support of my wife, Deirdre. While I worked on the manuscript, Deirdre
looked after everything else. And with three little ones (all under 6 years of age),
everything else was oftentimes quite a handful. Thanks, Deirdre.
Programming the Network with Perl 1st Edition Paul Barry
1
Meet Perl
This chapter introduces Perl to the non-Perl programmer. Competent Perl pro-
grammers need only skim through this material.
The main objective of this chapter is to provide sufficient Perl to allow read-
ers to comfortably work through the rest of Programming the Network with Perl.
Another is to show that Perl is a rather special programming technology: inter-
esting, powerful, useful and fun.
Newcomers to Perl are advised to work through a good introductory Perl text.
See the Print Resources section at the end of this chapter for suggestions.
For the purposes of this chapter, it is assumed that the reader is already a
programmer. Veterans of the ‘C type’ languages may find much of Perl familiar.
However, although Perl may look a lot like C, its behaviour is oftentimes a lit-
tle strange, and can consequently be quite unlike C. Fans of other programming
languages will, initially, just find Perl to be strange. Perl does not set out to be
strange, but it is sometimes so unlike the mainstream programming languages
that the differences are seen as strangeness in the eyes of ‘traditional’ program-
ming folk. Which leads into the first bit of Perl strangeness: default behaviour.
1.1 Perl’s Default Behaviour
Unlike other programming languages, Perl assumes a lot. It does a lot of things
by default, and unless told otherwise, a Perl program will inherit this default
behaviour. Think of this as Perl’s way of giving programmers something for noth-
ing. This is unlike the vast majority of programming languages, which generally
assume nothing, and where nothing is free.
2 Meet Perl
1.1.1 Our first Perl program
A simple example1
will help to illustrate this default behaviour:
#! /usr/bin/perl -w
while (<>)
{
print;
}
The first line (all that #! stuff) looks a little strange, so let us conveniently ignore it,
for now. The core of this program is the while loop, which is printing something
with a print statement. Just what is getting printed is not clear, but as the print
statement is in a loop, the assumption is that the printing is happening over and
over again (as long as the condition of the while loop is true). But, what is getting
printed?
The answer lies in the bit of code that has not been explained yet. No, not the
strange first line – that is still too strange to discuss – it is the other bit, the <>
bit. If you are reading this and saying ‘that cannot do much’, then welcome to the
wonderful world of Perl!
The <> is a Perl operator which, unless Perl is told otherwise, hooks a program
up to standard input and, when it appears in code, returns a line from standard
input to the program. Magically, the line of input comes into the program at the top
of the while loop, then makes its way (magically, again) to the print statement
and gets printed!
Now, if a selection of lines is fed to this program, they will all get printed one
after the other (remember: the print statement is within a loop, so the code
keeps executing while some condition is true). In this case, the program keeps
going while there are input lines to process. To get lines into the program, pass
them in from the keyboard (the hard way), or from a file (the easy way).
Use the vi editor to create a file containing the Perl code as shown above. For
want of a better name (and a distinct lack of imagination), let us call this program
first. At the Linux command prompt, enter the following command to test the
program’s functionality:
perl first /etc/passwd
The program should print each line from the /etc/passwd system file to the
screen, one line at a time, until it runs out of lines.
If something other than the content of the file appears, check to see if the Perl
code has been typed in correctly. You can ask Perl to check code for syntax errors
using the -c command-line switch. That is, typing perl -c first will check the
first program for errors, but not run it.
1Borrowed rather shamelessly from Chapter 2 of Nigel Chapman’s book: Perl: The Programmer’s
Companion. See the Print Resources section at the end of this chapter.
Perl’s Default Behaviour 3
So, this program will, by default, use the filename from the command-line as
standard input to the program. Perl finds the file, opens it, keeps reading from
the file one line at a time until there are no more lines to read, then closes the file
when the program ends. And all this behaviour happens by default.
As if that were not enough, the program actually does more. If it is provided
with more than one filename on the command-line, as follows:
perl first /etc/passwd /etc/inittab .bash_profile
it not only prints all the lines from /etc/passwd but, when it is done, moves
onto /etc/inittab and prints all the lines in that file, before moving onto
.bash_profile and printing any lines contained therein. Again, all this occurs
by default, free of charge, no questions asked!
A good question to ask at this point is: while the program is running, just where
does Perl put the line that it reads in with <> and then prints out with print? We
can answer this question after introducing another bit of Perl strangeness: the
default variable.
1.1.2 Perl’s default variable
Meet the default variable $_, the most used and abused variable in all of Perl.
The general rule-of-thumb is this: if a piece of Perl code expects a variable to
be used and one is not provided, 9 out of 10 pieces of code will use $_.
This is exactly what happens with <> and print in the first program. The
code could have been written as follows:
#! /usr/bin/perl -w
while ($_ = <>)
{
print $_;
}
To re-emphasize, this code is functionally identical to the code in the first pro-
gram (albeit, somewhat more explicit).
1.1.3 The strange first line explained
All that remains of the first program is an explanation of the strange #! line.
This line is actually doing two things. As the # symbol in Perl indicates the start
of a comment that extends to the end of the current line, the strange line is,
first and foremost, a comment that is ignored by the Perl interpreter. Secondly,
if the very first character of a file is # followed by a !, then the line takes on
special meaning on Linux (and UNIX-like) systems. The #! combination tells the
command processor to run the command identified by the rest of the line (in this
4 Meet Perl
case, it is the /usr/bin/perl -w part), and then send the rest of the file to it
as standard input. So, make the first program executable on Linux using the
following command:
chmod +x first
and then invoke the program as follows:
./first /etc/passwd /etc/inittab .bash_profile
Linux will find the Perl interpreter (rather conveniently called perl) located in the
/usr/bin directory and run the contents of the first file through it. This is a
cool feature of Linux (and UNIX), but of lesser importance if running on Mac OS
(prior to X) or one of the Windows varieties.
The -w part of the Perl command is a switch asking Perl to compile the code
with extra warnings enabled. Until you know what you are doing, the advice is to
always run Perl with the -w switch.
Oh, by the way (and in case you hadn’t noticed), Perl statements end with the ;
character, and blocks of code are enclosed in curly braces, { and }. Note, too, that
Perl is case sensitive (so be careful). And Perl is an interpreter, which means that
each time a program is run through Perl, the interpreter scans the code for errors,
converts the code to Perl’s internal bytecode format, optimizes the bytecode, then
runs it. If this all sounds slow, do not worry, in the big scheme of things, it really is
not. Once a Perl program is actually running inside the interpreter, its performance
compares favourably with the traditional compiled languages.
Whew! We are finally done with the first program. Which just goes to show
that it is sometimes much easier (and shorter) to write a few lines of Perl code
than it is to explain them!
1.2 Using Variables in Perl
So far, the only variable seen and used is $_, the default variable. Creating con-
tainers for variables in Perl is easy. Give the container a name (which is made up
of a combination of the letters A-Z, a-z, the digits 0-9 and the underscore charac-
ter), then precede the name with one of Perl’s special variable naming characters,
depending on what the variable will be used for:
$ – a scalar variable (one of something);
@ – an array variable (a collection of somethings, a list);
% – a hash variable (a collection of name/value pairs); and
 – a referenced variable (a ‘pointer’ to something else, usually another variable).
Using Variables in Perl 5
1.2.1 One of something: scalars
When looking for a place to put one copy of something within a Perl program, use
a scalar. Here are some examples:
$greeting = "Welcome to Perl!";
$score = 20;
$score = "Goal!";
$next = <>;
$_the_answer = 42;
$WhoWantsToBeA = 1_000_000;
Some readers may be looking at the $greeting variable and saying ‘that’s not
one of something, that’s three words’, but they would only be half right. Yes, it
is three words, but they are contained within one single string, and Perl refers to
this single string with a scalar variable container.
Other readers may find it interesting (even strange) that the variable $score is
being set to two different types of values – one a number (20) and the other a string
(‘Goal!’). Assuming that these six lines were in fact a little Perl program, surely the
Perl interpreter would complain that the second usage of $score causes an error,
as $score was initially used within a numeric context? On the contrary, Perl does
not care what value is assigned to a scalar2
, because Perl has no real notion of
variable types, at least not like that which readers might be used to in C, C++,
Pascal, or Java. So, it is OK (with Perl) to assign seemingly different typed values
to the same scalar variable.
Note that variable names can start with and include the underscore character,
which can also be used to make literal numbers easier to read – simply place an
underscore where it is usual to expect a comma. So:
$WhoWantsToBeA = 1_000_000;
is equivalent to:
$WhoWantsToBeA = 1000000;
whereas:
$WhoWantsToBeA = 1,000,000;
sets the variable $WhoWantsToBeA to 1, but readers will have to wait until lists
are covered to find out why.
In the code, the $next variable is assigned the result of Perl processing the <>
operator. What happens is that a line of text from standard input is read into
the program and assigned to the $next variable. Note that <> on a line by itself
within a program does not take a line from standard input and put it into the
$_ variable, as this behaviour only works within loops, as was the case with the
2Well, just so long as it is one of something.
6 Meet Perl
first program. Be warned: if the <> operator appears on a line by itself within a
Perl program, a line is read in from standard input, but, as Perl has nowhere to put
the contents of the line, it is discarded, never to be seen again (unless read again
from standard input). Hence, the use of the $next variable in the above example.
1.2.2 A collection of somethings: arrays and lists
Here is an example that shows a relatively standard usage of arrays and lists in
Perl:
@networks = (’Ethernet’, ’Token-Ring’, ’Frame-Relay’, ’ATM’);
On the left of the assignment operator (the = symbol), there is an array called
@networks. Note the prefixed @ character, which indicates that this is an array
variable. On the right, there are four network names in the form of a Perl list.
The four names are surrounded by single quotes, enclosed in parentheses, and
separated by commas. The elements of the list are all ‘one of something’ scalar
values (in this case, strings). This single line of code takes the four network names
and assigns them to the first four elements of the @networks array.
In Perl, array indices start counting from zero, and the first element is actually
referred to as element 0. So, @networks is a four-element array with elements
numbered 0, 1, 2 and 3.
The current size of an array can be determined in one of two ways. Add one to
the value of the largest index (using $#), or assign the array to a scalar variable:
print "The size of the array is: ", ( $#networks + 1 ), "n";
$size = @networks;
print "The size of the array is: $sizen";
will print the following:
The size of the array is: 4
The size of the array is: 4
Looking at the code, the $size scalar value is substituted into the part of the dou-
ble quoted string that gets printed. This process is called variable interpolation,
and it will be returned to later on in this chapter. The first print statement is
actually printing a list, made up of a string, an expression, and another string3
.
Arrays in Perl are automatically dynamic, so it is possible to add elements to
the array without first having to reserve space for them. Here is how to add more
network names into the array:
@networks = ( @networks, ( ’FDDI’, ’Arcnet’ ) );
3Did you notice this?
Using Variables in Perl 7
The $#networks variable now has the value 5, which means there are six elements
in the array.
Accessing a single, specific array element is accomplished using the standard
square bracket notation. The code which follows prints the word Token-Ring
(followed by the newline character):
print "$networks[1]n";
When accessing a single, specific element of an array, we are no longer referring to
a collection of somethings, we are instead referring to the single, scalar element
located within the array (i.e. one of something). Hence, the use of the $ prefix in
the previous example as opposed to the @ prefix, which would refer to the entire
array.
Surprisingly (or strangely), Perl does not complain when code refers to a sin-
gle array element with the @ prefix. The following code will also print the word
Token-Ring (followed by the newline character):
print "@networks[1]n";
Technically, this is a single element array slice, and should be avoided in situations
like this. Strange? Most definitely. Something to worry about? Probably not. Just
be sure to prefix single-element array accesses with $ and everything will be OK.
When used in a scalar context, arrays and lists have a value. An array has a
numeric value equal to the number of elements in the array, whereas a list has a
value equal to the first element in the list. This helps explain why the following
sets $WhoWantsToBeA to 1 and not 1,000,000 as might initially be expected:
$WhoWantsToBeA = 1,000,000;
Scalar context can be forced on an array by use of the inbuilt scalar subroutine.
This code tells Perl to treat the array as a scalar, even though it really still is an
array:
print "The size of the array is: ", scalar @networks, "n";
An experienced Perl programmer may frown at the initial technique used when
creating the first version of the @networks array, which is repeated here:
@networks = (’Ethernet’, ’Token-Ring’, ’Frame-Relay’, ’ATM’);
and could be rewritten as follows:
@networks = qw(Ethernet Token-Ring Frame-Relay ATM);
This has exactly the same meaning as the initial code, and many Perl programmers
prefer it (mainly due to the fact that the latter requires less typing). The qw is called
the quoting operator and is shorthand for ‘quote words’.
8 Meet Perl
1.2.3 Hashes
The third Perl variable container is the hash, more formally known as the asso-
ciative array. Hashes are somewhat like arrays, in that they hold a collection of
scalar somethings. However, whereas arrays are indexed using numeric values,
hashes are indexed using string values (which are also called ‘keys’ or ‘names’).
Each string value index has associated with it a scalar value. These associations
are often referred to as name/value pairs.
Hashes in Perl are prefixed with a % character. Here is a hash which will hold
data on the maximum frame size for a collection of popular networking technolo-
gies:
%net_mtus;
To refer to the entire hash, use the % prefixed name. To refer to an individual ele-
ment, prefix the hash name with the $ character (just as was done when referring
to individual array elements). Here is how to add an element (which is referred to
as a ‘hash entry’) into the newly created hash:
$net_mtus{’Ethernet’} = 1500;
The name (or key) is the word Ethernet and has the value 1500 associated with
it. Lists can be used to initialize a hash:
%net_mtus = ( ’Token-Ring’, 4464, ’PPP’, 1500, ’ATM’, 53 );
The list (which should have an even number of elements) is taken to contain a set
of name/value pairs. Note that this line of code refers to the entire hash using the
% prefix. This is shorthand for the following functionally identical code:
$net_mtus{’Token-Ring’} = 4464;
$net_mtus{’PPP’} = 1500;
$net_mtus{’ATM’} = 53;
Yet another version of this code takes advantage of the Perl feature which aliases
the => symbol with the comma. Additional (entirely optional) white space adds to
the readability of this code, and helps to highlight the name/value pairs:
%net_mtus = ( ’Token-Ring’ => 4464,
’PPP’ => 1500,
’ATM’ => 53 );
It is often useful to think of => as meaning ‘has the value’ when working with
hashes.
Of note here is that, just like arrays, hashes grow dynamically and automatically
in Perl. Also important is the fact that hash keys are (and must be) unique4
.
4The same restriction applies to array indices, although there tends to be much less fuss made
of this fact.
Using Variables in Perl 9
When a hash entry is created, a value part does not need to be initially specified.
The special value undef can be used to set a hash entry (or any variable) to the
undefined value:
$net_mtus{’SMDS’} = undef;
The above code is identical to:
$net_mtus{SMDS} = undef;
the only difference being that the single quotes are missing around the SMDS. In
‘Perl-speak’, this is referred to as a bareword. If a hash name contains no white-
space, the single quotes are generally not required.
A convenient way to clear an entire hash is to set it equal to an empty list:
%net_mtus = ();
Hashes (and arrays, for that matter) are very useful ‘right out-of-the-box’. For the
vast majority of the programs in Programming the Network with Perl, these inbuilt
variable containers are all that is needed. However, on occasion, more complicated
data structures help to simplify a solution. The problem with arrays and hashes
is that they can only store scalar values. This restriction, on first glance, seems
limiting in that it appears no method exists to provide for, say, storing an array in
a hash entry, or storing a hash in an array element. This restriction is overcome
by the use of references.
1.2.4 References
A reference is a Perl scalar variable container that refers to something else. The
‘something else’ can be one of a number of things, including another scalar, array,
hash, subroutine, or Perl object. In this subsection, references to scalars, arrays
and hashes are described. References to subroutines and objects will be discussed
in later sections.
If a scalar reference refers to an array, the scalar reference can then be, for
example, added to an existing hash, creating a hash entry that refers to an array.
The entry in the hash is still a scalar value (satisfying the restriction placed on
hash values), but as a reference, it now refers to something more complicated
than a scalar – in this case, an array.
Creating a reference is very easy. Simply place a  before the thing to be refer-
enced. Here is code which creates a reference to an existing array, then adds the
reference into an existing hash:
%networks = ();
@ethernets = qw( Ethernet-II IEEE802.3 IEEE802.3-SNAP );
$e_ref = @ethernets;
$networks{’Ethernet Standards’} = $e_ref;
10 Meet Perl
The ’Ethernet Standards’ hash entry now refers to the @ethernets array. It
is important to realize that the @ethernets array and the $e_ref scalar both
refer to the same data. If the array is changed, then what the scalar refers to also
changes. Think of the scalar reference as an alias to the array’s memory location.
To access the array (referred to in the hash), dereference the hash entry:
print "The Ethernet standards are: ";
print "@{$networks{’Ethernet Standards’}}n";
As it is known that the $networks{’Ethernet Standards’} entry is a reference
to an array, prefix the use of the hash entry with the @ symbol. (The hash entry is
also enclosed in an extra pair of curly braces, although this is not strictly required.)
Read this code as: ‘access the array referred to by the hash entry’.
In the earlier code, the use of the $e_ref scalar is redundant. It is equally valid
to write the code this way:
%networks = ();
@ethernets = qw( Ethernet-II IEEE802.3 IEEE802.3-SNAP );
$networks{’Ethernet Standards’} = @ethernets;
Even this can be shortened, if the sole purpose of having the @ethernets array is
to create a reference to it within a hash entry. Here is another, equally valid, way
to code this:
%networks = ();
$networks{’Ethernet Standards’} =
[ ’Ethernet-II’, ’IEEE802.3’, ’IEEE802.3-SNAP’ ];
By enclosing the list of array elements in square brackets, this code creates an
anonymous array (i.e. one that has no name). The array is then assigned to a hash
entry, and Perl is smart enough to use a reference.
Here is some code which shows the creation and use of references to scalars
and hashes:
$scalar = 42;
$refs = $scalar;
print ’Both $scalar and $refs have the value: ’, ${$refs}, ".n";
%hash = ( ’Name’ => "Paul Barry",
’Book’ => "Programming the Network with Perl",
’Year’ => 2002 );
$array_of_hashes[0] = %hash;
print "There’s a great book called ";
print "${$array_of_hashes[0]}{’Book’} byn";
print "${$array_of_hashes[0]}{’Name’}, published in ";
print "${$array_of_hashes[0]}{’Year’}.n";
Using Variables in Perl 11
Unfortunately, as shown in this piece of code, the syntax for accessing an indi-
vidual hash entry within an array of hashes is complex. To yield the string ‘Paul
Barry’ from the array of hashes, the code referred to it as:
${$array_of_hashes[0]}{’Name’}
which reads (from the inside out): ‘take whatever is at element zero of the
@array_of_hashes array, treat it as a hash, then access the value paired with
the Name key’. Thankfully, Perl provides an alternative syntax, which can reduce
this level of complexity. It is possible to yield ‘Paul Barry’ like this:
$array_of_hashes[0]->{’Name’}
or like this:
$array_of_hashes[0]{’Name’}
When the -> appears between a right and left bracket pair – either ]{, }[, }{, or
][ – its use is not required.
It is also possible to create and use anonymous hashes by enclosing the hash
entries in curly braces. Here is another (equally valid) way to populate the first
element of the $array_of_hashes array:
$array_of_hashes[0] =
{ ’Name’ => "Paul Barry",
’Book’ => "Programming the Network with Perl",
’Year’ => 2002 };
Or, this code would also do:
%hash = ( ’Name’ => "Paul Barry",
’Book’ => "Programming the Network with Perl",
’Year’ => 2002 );
$array_of_hashes[0] = { %hash };
When working with the %networks hash of arrays (from earlier), either of the
following work, yielding the string ‘IEEE802.3’:
${$networks{’Ethernet Standards’}}[1];
$networks{’Ethernet Standards’}->[1];
$networks{’Ethernet Standards’}[1];
Which technique to use is a programmer preference, but be aware that many Perl
programmers freely mix their use of each, so it is important to be able to recognize
all of them.
To check if some variable is a reference, use the inbuilt ref subroutine, which
returns the type of reference as a string.
12 Meet Perl
1.2.5 Built-in variables
The Perl interpreter defines (and uses) a large collection of built-in variables. The
default variable ($_) has already been described. A full list of built-ins can be
viewed in the perlvar manual page. Type this command at the Linux command-
line to page through the material:
man perlvar
Here is a list of frequently used built-in variables (examples of their use – with
explanations – appear throughout Programming the Network with Perl).
$! – contains the operating system error code after some operation has failed.
$| – the auto-flush variable, which when set to 1 switches off buffering when Perl
writes to an output filehandle (such as standard output). With auto-flushing
off, the output buffer will typically not get flushed until a newline character
is written.
$1, $2, etc. – the pattern-match variables, created as the result of successful pat-
tern matches and regular expressions.
$a, $b – used by the inbuilt sort subroutine when doing comparisons.
$@ – when eval is used, $@ is set upon the return from eval.
@_ – the default array, used when processing parameters inside Perl subroutines.
@ARGV – contains the list of command-line parameters sent to a program.
@INC – lists the series of directories Perl searches when loading (and looking for)
add-on modules.
%ENV – a hash containing the current contents of the operating systems environ-
ment.
%SIG – a hash of operating system signals and signal handlers.
1.2.6 Scoping with local, my and our
Variable containers in Perl need not be declared prior to their first use. Perl will
automatically create them as needed. As a direct result of this behaviour, all vari-
able containers in Perl are global in scope.
It is possible to localize a global variable container to a block of code using
the inbuilt local subroutine. When local is used in a block, at the end of the
block the variable will revert to the value it had prior to entering the block within
which it appears. Within the block, the variable can be used in any which way. If
the block of code invokes a subroutine, the local value is visible (not the global)
within the invoked subroutine. Due to its strange behaviour, use of local tends
to be frowned upon nowadays. Consequently, none of the code in Programming
the Network with Perl uses local.
Controlling Flow 13
The inbuilt my subroutine can be used to give a variable container lexical scope.
The variable is not globally visible, nor is it visible by any invoked subroutine. It
is only visible within the block that declares it. When the use strict compiler
directive is used at the top of a Perl program, global variables are forbidden, and
my must be used. That is, of course, assuming the variable containers have not
been declared with our.
The inbuilt our subroutine is new as of release 5.6.0 of Perl. When our is used,
the variable container can be used as if it is global, even though it really is not.
This allows a program to use the use strict compiler directive, and still use
global variable containers when it is convenient (or necessary) to do so.
1.3 Controlling Flow
Perl has the usual collection of flow control statements: if, while and for. Perl
also has some of its own: unless, until and foreach. In addition, two built-
in subroutines (do and eval) can impact on a program’s flow of control. In this
section, we will look at each of these constructs in turn.
1.3.1 if
To decide on one or more courses of action, use the if statement. Assuming
the $net scalar is set to an appropriate value, a simple if statement might
be:
if ( $net eq ’Token-Ring’ )
{
print "The network is of the token passing variety.n";
}
This code prints the message if the condition-part (i.e. the first line) of the if
statement is true. Veterans of the C-type programming languages need to note that
the use of curly braces is required by Perl. Two-way decisions are accommodated
by the use of an else statement:
if ( $net eq ’Token-Ring’ )
{
print "The network is of the token passing variety.n";
}
else
{
print "The network is NOT a token passer.n";
}
Multi-way decisions are also possible (note the strange spelling of elsif):
14 Meet Perl
if ( $net eq ’Token-Ring’ )
{
print "Your network is of the token-passing variety.n";
}
elsif ( $net eq ’Ethernet’ )
{
print "Your network is of the CSMA/CD variety.n";
}
elsif ( $net eq ’Frame-Relay’ )
{
print "Your network is of the ISDN variety.n";
}
else # Assuming a value of ’ATM’ ...
{
print "Your network is of the cell-switching variety.n";
}
This is the only way to perform a multi-way decision in Perl. C and Java program-
mers may miss the convenience of the switch statement, just as Pascal program-
mers may miss their case statement. To such programmers, Perl offers nothing
more than a shrug of apology (and a nod in the direction of code similar to that
shown above).
1.3.2 The ternary conditional operator
Perl supports the ternary conditional operator. The following if statement sets
the value of $do depending on the current value of $today:
if ( ($today eq ’Sat’) or ($today eq ’Sun’) )
{
$do = "Play";
}
else
{
$do = "Work";
}
and is functionally identical to this (somewhat more compact) code:
$do = ( ($today eq ’Sat’) or ($today eq ’Sun’) ) ? "Play" : "Work";
The condition-part of the if statement comes before the ? symbol. If the
condition-part is true, the value Play results, otherwise the value Work results
(with the : symbol separating the two possible results). The variable $do is, there-
fore, assigned an appropriate value.
Controlling Flow 15
1.3.3 while
The while statement was part of the first program written at the start of this
chapter. Like the if, curly braces are required with while statements.
Code inside the loop (i.e. within the curly braces) keeps executing while the
condition-part of the while statement is true. A loop can optionally include a
continue block which will execute at the end of each loop (or iteration).
Three statements provide programmers with the ability to fine tune the
behaviour of loops:
next – jump immediately to the bottom of the loop and execute the continue
block (if one exists), then start a new iteration if the condition-part evaluates
to true;
last – exit the loop, bypassing any continue block, and resume execution at the
first statement immediately following the loop;
redo – abandon the current iteration of the loop, jump to the first statement of
the loop, and re-execute the loop statements.
Example uses (with explanations where required) of these statements appear
throughout Programming the Network with Perl.
The while statement is often used to iterate through a hash, as follows:
while ( ($name, $value) = each %net_mtus )
{
print "$name has the value: $valuen";
}
The inbuilt each subroutine returns a name/value pair from the specified hash,
and with each iteration, the next name/value pair is returned until no more pairs
are left. Of note is that the name/value pairs come out of the hash in no particular
order (and most definitely not in the order that they were inserted).
1.3.4 for
The for statement iterates a fixed number of times over code, and is typically
used to process arrays. Here is how to print each element of the @networks array
on its own line:
for ($i = 0; $i <= $#networks; $i++)
{
print "$networks[$i]n";
}
This code initializes $i to zero before the loop starts to iterate, then checks
to see if the value of $i is less than or equal to the largest index of the array
($#networks). If it is, the loop iterates, then the value of $i is incremented after
16 Meet Perl
the iteration completes, and prior to the test against $#networks is performed
again. The loop iterates until the entire array has been printed.
1.3.5 unless
In Perl, the unless statement is the opposite of if. This code prints the line for
values of $net other than Token-Ring:
unless ( $net eq ’Token-Ring’ )
{
print "The network is NOT of the token passing variety.n";
}
The unless statement can have an else part, but no elsifs.
1.3.6 until
The while statement also has an opposite, the until statement. Rather than
iterating while a condition is true, this statement iterates until some condition is
true.
1.3.7 foreach
The for statement described earlier is used so often to process arrays that a
special shorthand version exists, the foreach statement. This code is identical to
the example used with for above:
foreach $i (@networks)
{
print "$in";
}
But be careful: while inside the loop, the $i variable is an alias to the actual
element within the @networks array. If $i is changed, so is the corresponding
array element.
The foreach statement can also be used to iterate over a hash:
foreach $name ( keys %net_mtus )
{
print "$name has the value: $net_mtus{$name}n";
}
Another inbuilt subroutine, keys, returns a list of all the name-parts of the named
hash. This list (array) is then used normally by the foreach. The keys subroutine
can also be used, in conjunction with scalar to calculate the number of elements
in any hash:
Controlling Flow 17
$size = scalar keys %net_mtus;
print "The size of the hash is: $sizen";
A common extension to the above hash traversal code is to call the sort or
reverse inbuilt subroutine to force an ordering on the hash name-parts:
foreach $name ( sort ( keys %net_mtus ) )
{
print "$name has the value: $net_mtus{$name}n";
}
1.3.8 do
The do subroutine takes a block of code as its sole parameter, and executes the
block of code, returning the value of the last line of the code as the result of the
do.
The following example sets the value of $res to 15, then prints the value to the
screen, and illustrates the basic mechanism:
$res = do
{
$a = 5;
$b = 3;
$a * $b;
};
print $res;
A second form of do takes the name of a file as its sole parameter and executes
the contents of the file as a Perl program. Assuming a file called es1 exists in
the current working directory, this code opens the file from within the current
program and runs any Perl code contained therein:
do ’es1’;
1.3.9 eval
The eval subroutine takes a string as its sole parameter and executes the string
as a Perl program (or fragment thereof). This code does the same thing as the do
example:
$some_code = ’$a = 5; $b = 3; $res = $a * $b; print $res;’;
eval { $some_code };
What makes this eval code different5
from the equivalent do code is that a certain
amount of protection is provided by eval. Specifically, if the code within the eval
5Some would say ‘better’.
18 Meet Perl
block causes a fatal error (which would normally cause the Perl interpreter to exit
immediately from a program), eval catches the fatal error and provides a way to
recover from the error. The built-in variable $@ will be set by eval on exit from the
code block. If the value of $@ is set to the empty string, no fatal error occurred.
However, if the value of $@ contains a non-empty string, a fatal error occurred and
a description of the error is in $@. This, therefore, provides a simple, yet highly
useful, exception-handling mechanism.
In the code which follows, a call to the inbuilt die subroutine causes the gen-
eration of a fatal error (and message). When called outside an eval block, the
program would end immediately. When called inside an eval block, the evalu-
ated code ends and the $@ variable is set to the message from die.
Here is an eval example:
eval
{
print "This is Apollo 13. Mission Log.n";
print "We are half-way to the Moon.n";
die "Houston, we have a problem!n";
};
if ($@)
{
print "Message from Apollo 13 - $@";
print "Let’s bring them home safely ... ";
}
else
{
print "Maybe 13 is not that unlucky after-all ... ";
}
Due to the fact that the call to die is within the eval block, the program can
recover gracefully from what would otherwise be a fatal error (and go on to save
the astronauts). The else part of the if statement will never execute in this code,
but is included here for illustration only.
1.3.10 Statement modifiers
In addition to the control flow mechanisms which enclose blocks of code, Perl
also provides support for statement modifiers. With these, individual statements
can be qualified. A series of examples will help to illustrate.
This code prints the words ‘Hello World’ if the value of $should_we has some
value (i.e. if it is defined):
print "Hello World" if defined( $should_we );
This code prints the words ‘Hello World’ unless the value of $today is Saturday:
print "Hello World" unless $today eq ’Saturday’;
Boolean in Perl 19
This single line of code is another way of writing the first program from the
start of the chapter. The code takes lines of input from standard input (one at a
time) and prints them. It keeps going until there is no more input lines to process:
print while (<>);
It is possible to use until anywhere that while is used, and this is also true of
statement modifiers. When combined with do, statement modifiers provide for
loops that will iterate at least once, as the condition-part of the loop comes at the
end of the block. Here is the general form of the do. . .while construct:
do
{
# Do something ...
}
while # some condition is true;
and here’s the general form of a do. . .until:
do
{
# Do something ...
}
until # some condition is true;
1.4 Boolean in Perl
Strangely, Perl has no inbuilt Boolean type6
. Instead, any Perl expression can be
used as a condition, and can be evaluated to be either true or false. A number of
rules help determine whether something is true or false as follows.
Strings – a string is true, unless it contains "0" or the empty string. (Strangely,
"00" and "0.00" are true.)
Numbers – a number is true, unless it evaluates to zero. (Strangely, this means
−42 is true.)
References – all references are true. (This is initially quite strange until one con-
siders what a reference contains.)
Undefs – anything with the undefined value is false. (This is not strange – how
can anything that is undefined possibly be true?)
Lists – empty lists are false, lists with any number of elements are true. (Like
undef, this is not at all strange.)
6Are you not getting used to all this Perl strangeness yet? After a while, it all becomes quite
normal. Strange, but true.
20 Meet Perl
1.5 Perl Operators
In a number of the code examples seen so far, various code snippets have relied
on condition tests that have used comparison operators. They have been rather
sneakily used, without providing any detailed description. Nobody likes a sneak,
so here is the entire list of Perl operators (with brief explanations) in precedence
order, starting with those with the highest precedence.
-> – the infix dereference arrow operator, used when working with references
(and objects).
++ and -- – the increment and decrement operators.
** – the exponential operator.
!, ˜, , + and - – the logical negation (!), bit-wise negation (˜), reference (),
numeric affirmation (+) and arithmetic negation (-) operators.
=˜ and !˜ – the binding operators (used when working with regular expressions
and pattern matches).
*, /, % and x – the multiply, divide, modulus (%) and repetition (x) operators.
+, - and . – the addition, subtraction and concatenation (.) operators.
<< and >> – the left and right bit shifting operators.
<, >, <=, >=, lt, gt, le and ge – the relational operators. There are two of each,
one for working with numbers and the other for working with strings. Be
careful to use <, >, <= and >= when comparing numbers, and use lt, gt, le
and ge when comparing strings.
==, !=, <=>, eq, ne and cmp – the equality operators. As with the relational oper-
ators, different versions exist for use with numbers and for strings. The <=>
and cmp operators are used for comparison, and are typically used in con-
junction with the inbuilt sort subroutine.
& – the bit-wise AND operator.
| and ˆ – the bit-wise OR and eXclusive OR operators.
&& – the logical AND operator.
|| – the logical OR operator.
.. and ... – the range operators.
?: – the ternary conditional operator.
=, **=, +=, *=, &= and so on – the assignment operators.
, and => – the comma operator (typically used to separate list items).
not – a lower precedence alternative to !.
and – a lower precedence alternative to &&.
Subroutines 21
or and xor – lower precedence alternatives to || and a logical eXclusive OR oper-
ator.
1.6 Subroutines
Perl supports the creation of named, user-defined blocks of code, which go by the
generic name of ‘subroutine’7
. Creating subroutines could not be easier: give the
subroutine a name, pass the name to the inbuilt sub subroutine together with the
block of code. Here is a simple example:
sub simple {
print "Hello from the simple subroutine!n";
}
The subroutine can now be invoked (from within the program that defined it) in
one of four ways:
simple;
simple();
&simple;
&simple();
It rarely matters which of these techniques is used, as they all do the same thing,
i.e. invoke simple. When Perl gets picky about a particular style of invocation, the
interpreter will tell you.
1.6.1 Processing parameters
Every user-defined Perl subroutine can take any number of parameters. If simple
was invoked as:
simple( "Hey! Print this!n" );
it would simply ignore the parameter, and Perl would not complain. Any parame-
ters that are sent to a subroutine become available within the default array, which
is called @_. Here is another version of simple that can process parameters:
sub simple {
$print_what = $_[0];
print $print_what;
}
where $_[0] refers to the first element of the @_ array. To print the entire array
contents, use this code:
7Also known as ‘function’, ‘procedure’, ‘routine’ and/or ‘method’, depending on your program-
ming background.
22 Meet Perl
sub simple {
print "@_";
}
If more than one parameter is passed, each becomes available within the subrou-
tine as a separately accessible array element. Let us assume that another version
of simple supports calls like this:
simple( "On line one", "On line two" );
To access each ‘line’ within simple, the subroutine could be rewritten to access
each element of the default array:
sub simple {
print $_[0], "n";
print $_[1], "n";
}
This technique is rarely seen, as most seasoned Perl programmers prefer to take
advantage of the inbuilt shift subroutine, which removes and returns the first
element from a named array, or the first element from the default array if no array
is specified. Once again, a rewritten simple illustrates this technique:
sub simple {
print shift, "n";
print shift, "n";
}
It is important to realize that when parameters are passed to any user-defined
subroutine, they are ‘flattened’ into a list. So, if a subroutine is written to expect as
parameters a hash, followed by an array, and then a scalar, the three parameters
will enter the subroutine as one long, flattened list (which is rarely what was
wanted). Pass the hash, array, and scalar as references to ensure they arrive in
the subroutine in the correct format. In this case, the @_ default array will contain
three elements: a hash reference, an array reference, and a scalar reference. Note,
too, that when accessed inside the subroutine, the references refer to the original
variable containers, so if they are changed within the subroutine, they will be
changed elsewhere. By default, all parameters are passed by value.
1.6.2 Returning results
A subroutine can return a value, and unless explicitly stated, this will be the value
of the last statement in the subroutine. The simple subroutine would therefore
return a true value (assuming the call to print was successful). To control what
value is returned, use the inbuilt return subroutine:
Subroutines 23
sub simple {
my $count = 0;
print shift, "n";
$count++;
print shift, "n";
$count++;
return( $count );
}
This code will (always) return the value 2.
1.6.3 I want an array
Perl subroutines can be written to return either a scalar or a list. Consider the
inbuilt keys subroutine introduced during the discussion of hashes. When called
in what is known as list context, keys returns a list of hash name-values. When
called in scalar context, keys returns the number of elements in the hash.
By employing the services of the inbuilt wantarray subroutine, it is possible to
write a user-defined subroutine that works in a similar fashion:
sub return_hash_keys {
%a_hash = @_;
return ( wantarray ? keys %a_hash : scalar keys %a_hash );
}
%net_mtus = ( ’Token-Ring’ => 4464,
’PPP’ => 1500,
’ATM’ => 53 );
@keys = return_hash_keys( %net_mtus );
print "Hash keys: @keysn";
$size = return_hash_keys( %net_mtus );
print "Hash size: $sizen";
The wantarray subroutine knows whether the user-defined subroutine has been
called in list or scalar context. If called in list context, wantarray evaluates to
true.
1.6.4 In-built subroutines
Perl has a large collection of inbuilt subroutines. The entire collection is docu-
mented in the perlfunc online documentation. Use this command to view the
manpage:
man perlfunc
24 Meet Perl
Alternatively, use the perldoc program (which comes with Perl) to search the
perlfunc manpage for documentation on a specific subroutine. For instance, to
view the documentation for the inbuilt print subroutine, use this command:
perldoc -f print
The inbuilt subroutines take a varying number of parameters. Check the documen-
tation for specifics. Be aware that some inbuilt subroutines can do different things
based on how they are invoked and used. The code in this chapter has already
used some of the more popular inbuilt subroutines. Here is an abbreviated list8
:
alarm – signal an alarm to occur a number of seconds in the future;
chomp – deletes the trailing newline character from a scalar;
chop – deletes the last character from a scalar;
close – close a previously opened filehandle;
defined – returns true if a variable has a value associated with it;
delete – delete elements/entries from an array/hash;
die – exit the current program after displaying a user-specified message;
do – execute a block of statements as one, or read in a collection of statements
from another file and execute them;
each – used to iterate over a hash;
eof – test for the end-of-file condition;
eval – evaluate a block of code, and provide exception handling;
exists – returns true if a specific array element or hash entry exists;
exit – exit the current program;
fork – create a child process which is a clone of the current process;
gmtime – return the date and time relative to GMT;
goto – jump to a labelled location within a program9
;
join – join a list of strings together;
keys – returns a list of keys for a specified hash;
last – exit from the current loop;
length – return the length of a scalar variable;
local – localize a variable;
localtime – return the date and time relative to the local time zone;
my – mark a variable as being lexically scoped;
8Subroutines of specific interest to network programmers are not presented here, as they are the
subject of Chapter 3.
9But real programmers never use goto, do they?
Subroutines 25
next – start the next iteration of the current loop;
open – open a file, and associate a filehandle with it;
our – declare a global variable;
pack – convert a collection of variables into a string of bytes;
package – declare a new namespace;
pop – treat an array like a stack, and pop the last element off the end of the array;
print – print something (to a named output handle);
printf – print to a particular format;
push – treat an array like a stack, then push an element onto the end of the array;
read – read a specified number of bytes from a filehandle;
redo – restart the current loop iteration;
ref – check to see whether a scalar is a reference, and if it is, return the type of
reference as a string;
return – return a value from a subroutine;
scalar – force a list to be treated as if it were a scalar;
shift – treat an array like a stack, and pop the first element off the start of the
array;
sleep – pause execution for a specified number of seconds;
sort – sort a list using string comparison order (by default), or by using some
user-specified ordering;
splice – remove specified elements from an array;
split – split a delimited string into a list of individual elements;
sprintf – like printf, except the result is assigned to a scalar;
sub – declare a subroutine;
substr – extract a substring from a string;
system – call an operating system command, and return its exit status to the
calling program;
time – returns the number of non-leap seconds since the operating system’s
‘epoch’10
;
undef – take a previously defined variable, and undefine it;
unpack – the reverse of pack: extract a list of values from a string of bytes;
unshift – treat an array like a stack, and push an element onto the start of the
array;
wait – wait for a previously created child process to terminate;
10What the operating system thinks is the start of time. It varies from system to system.
26 Meet Perl
wantarray – return true if a subroutine was called within a list context, false
otherwise;
warn – sends output to standard error;
write – write a specified number of bytes to a filehandle.
Example uses of these inbuilt subroutines appear throughput Programming the
Network with Perl. If their meaning is not clear from the context in which they are
used, further description is provided.
1.6.5 References to subroutines
Perl allows references to subroutines.
Here is a preview of a code snippet from the end of Chapter 2 which assigns a
subroutine reference to a scalar called $packet_handler based on the value of
another scalar called $opt_u:
if ($opt_u)
{
$packet_handler = &udp_both_packet;
}
else
{
$packet_handler = &tcp_both_packet;
}
Note the use of the  character which turns the call to the subroutine into a refer-
ence to the subroutine. Later in the code, the previously selected subroutine can
be invoked as follows:
&$packet_handler;
1.7 Perl I/O
Performing input and output (I/O) in Perl is as simple as it gets. Disk files have
associated filehandles, and each time some input and output is performed, the
code need only reference the correct filehandle to work. Filehandles can be opened
to read from, write to, or read/write to/from.
Four filehandles are automatically opened for every Perl program: STDIN, STD-
OUT, STDERR, and DATA. These correspond to standard input (usually the key-
board), standard output (usually the screen), standard error (usually the screen,
but sometimes a system log file), and the thoroughly strange ‘standard data’. The
DATA filehandle is associated with anything that comes after the __END__ symbol
at the end of a source code file, and is generally useful when testing code prior to
deployment.
Perl I/O 27
To read from a filehandle, enclose the filehandle in the <> angle brackets. This
code reads a line from standard input:
$line = <STDIN>;
which is longhand for:
$line = <>;
as Perl will assume standard input by default. Writing to output filehandles usually
involves the use of the inbuilt print subroutine. Here is how to write to standard
output:
print STDOUT "Writing to standard output, usually the screen.n";
which is longhand for:
print "Writing to standard output, usually the screen.n";
as Perl will assume standard output by default. To write to standard error, use
code similar to this:
print STDERR "Writing to standard error.n";
or use the inbuilt warn subroutine which will always write to STDERR:
warn "Writing to standard error.n";
To create filehandles, give them a name and associate them with a file. By conven-
tion, filehandle names are specified in uppercase, although Perl does not enforce
this as a rule. To open a file for reading, use code similar to the following:
open MYINFILE, "readme.txt" or die "Could not open: $!";
This code will open readme.txt and associate it with the MYINFILE filehandle,
or if something goes wrong, exit with an appropriate error message.
Once a filehandle is opened, read from it using the <> operator:
$a_line = <MYINFILE>;
@entire_file = <MYINFILE>;
Here the <> operator is used in both scalar and list context. Be careful when
using <> in list context, as reading a large file in one go can result in memory
problems.
To close a filehandle, call close on the filehandle name:
close MYINFILE;
which Perl will do anyway when your program ends.
Another Random Scribd Document
with Unrelated Content
In December Suchet completed the formal conquest of Aragon,
by moving up the whole of Laval’s division into the high-lying district
of Teruel, in the extreme south-east of the province, the only part of
it that had never yet seen the French eagles. The Junta of Aragon
fled from thence over the border of the kingdom of Valencia, but
Villacampa and his bands remained in the mountains unsubdued,
and while they continued to exist the conquest of the upland was
incomplete. The moment that its towns ceased to be held by large
garrisons, it was clear that the insurgents would descend to
reoccupy them. Nevertheless Suchet had done much in this year:
besides the crushing of Blake he had accomplished the complete
subjection of the plains of Central Aragon, and had obtained a grip
upon its two mountain regions. He had fortified Monzon, Fraga,
Alcañiz, and Caspe as outposts against the Catalans, and, having
received large drafts from France in the autumn, was on the last day
of the year at the head of a fine corps of 26,000 men, from which he
might hope to produce in the next spring a field army sufficient for
offensive operations against Catalonia or Valencia, after providing
garrisons for his various posts of strength[16]
. The weak point of his
position was that the guerrilleros had learned caution, refused for
the future to fight save under the most favourable conditions, and
devoted themselves to the safe and vexatious policy of intercepting
communications and cutting up small parties and stragglers. They
were much harder to deal with, when once they had learnt that not
even in fastnesses like El Tremendal or San Juan de la Peña was it
wise to offer the French battle. Unless Suchet left a garrison in every
town, nay, in every considerable village, of the sierras, the
insurgents dominated the whole region. If he did take such
measures for holding down the upland, he was forced to immobilize
a very large proportion of his army. We shall note that in 1810 he
was only able to draw out 12,000 of his 26,000 men for the invasion
of Western Catalonia.
While the commander of the 3rd Corps was making steady
progress with the conquest of Aragon, the fortunes of his colleague
of the 7th Corps had been far more chequered. Indeed for the
greater part of 1809 St. Cyr was brought to a complete standstill by
the unexpected obstinacy of the gallant garrison of Gerona, who for
no less than eight months kept the main body of the army of
Catalonia detained in front of their walls.
When last we dealt with the operations in this region we left St.
Cyr victorious at the well-contested battle of Valls, after which he
advanced into the plain of Tarragona, made some demonstrations
against that fortress, but returned after a few weeks to Barcelona
(March 18) without having made any serious attempt to turn his
victory to practical account. This retreat after a brilliant success may
be compared to Victor’s similar evacuation of Southern Estremadura
after Medellin, and was brought about, in the main, by the same
cause, want of supplies. For when he had consumed the resources
of the newly-subdued district between Valls and Tarragona, St. Cyr
had no means of providing his army with further subsistence.
Barcelona, his base, could not feed him, for the city was itself on the
edge of famine: it was still beset to north and west by the local
miqueletes, who had returned to their old haunts when the main
French army had gone off southward on the campaign of Valls. It
was stringently blockaded on the sea side by the British
Mediterranean fleet, and it could not draw food from France by land,
because the high-road to Perpignan passed through the fortress of
Gerona, which was still in Spanish hands. St. Cyr himself, it will be
remembered, had only reached Barcelona by turning off on to side
tracks through the mountain, and winning his way down to the shore
by the hard-fought battle of Cardadeu. Till Gerona should fall, and
the garrison of Barcelona be placed in direct communication with
France, there was little use in making ambitious offensive
movements against Tarragona or any other point in Southern or
Central Catalonia. It was absolutely necessary to reduce Gerona, and
so to bring the division left behind under Reille, in the Ampurdam
and on the frontier of Roussillon, into free communication with the
remainder of the 7th Corps. From the moment when St. Cyr passed
the mountains during the winter Reille had been fighting out a petty
campaign against the northern Catalans, which had no connexion
whatever with his superior’s operations at Molins de Rey and Valls,
and had little definite result of any kind.
No one saw more clearly than Napoleon the need for the
reduction of Gerona: as early as January he had issued orders both
to St. Cyr and to Reille to prepare for the enterprise. But St. Cyr was
now out of touch, and Reille was far too weak in the early spring to
dream of any such an adventure: he had been left no more than
seven depleted battalions to maintain his hold on Northern
Catalonia, when St. Cyr took the rest of the army across the hills to
Barcelona. The Emperor was not slow to realize that the 7th Corps
must be reinforced on a large scale. He did so by sending thither in
the spring of 1809 a brigade of Berg troops (four battalions), the
regiment of Würzburg (two battalions), and a division (seven
battalions) of Westphalians: it will be noted that now, as always, he
was most chary of drafting native French troops to Catalonia, and
always fed the war in that direction with auxiliaries in whose fate he
was little interested: the campaign in eastern Spain was, after all,
but a side issue in the main struggle[17]
. When these reinforcements
had arrived Reille began to collect material at Bascara on the Fluvia,
to which siege-guns laboriously dragged across the Pyrenees were
added: several companies of heavy artillery and sappers were
brought up from France.
St. Cyr meanwhile, four weeks after his retreat from the plain of
Tarragona, moved on to Vich upon April 18, with the divisions of
Souham, Pino, Lecchi, and Chabot, leaving Duhesme with his original
French division, which had held Barcelona since the outbreak of the
war, in charge of his base of operations. His departure was partly
designed to spare the stores of Barcelona, where the pinch of
famine was beginning to be felt; for he intended to subsist his army
on the upland plain of Vich, a rich corn-bearing district hitherto
untouched by the war. But a few days after he had marched forth
Barcelona was freed from privation, by the lucky arrival of a
squadron of victuallers from Toulon, convoyed by Admiral Cosmao,
which had put to sea in a storm and eluded the British blockading
squadron (April 27). The position of Vich, however, had been chosen
by St. Cyr not only for reasons of supply, but because the place was
happily situated for covering the projected siege of Gerona against
any interruption by Blake. If the Spanish commander-in-chief
brought up the wrecks of the old Catalan army from Tarragona, with
his Valencian levies added, he would almost certainly take the inland
road by Manresa and Vich, since the coast-road was practically
barred to him by the French occupation of Barcelona. As a matter of
fact the commencement of the leaguer of Gerona was not vexed by
any such interruption, for Blake had his eyes fixed on Saragossa in
May and June, and was so far from dreaming of an assault on St.
Cyr, that he drew off part of the Catalan army for his unhappy
invasion of Aragon, which finished with the disaster of Belchite.
During the early months of this long siege the only external helpers
of the garrison of Gerona were the small force of regulars under the
Swiss Wimpfen, and the miqueletes of Claros and Rovira from the
Ampurdam, Reille’s opponents during the spring. At Tarragona the
Marquis of Coupigny, the senior officer now in Catalonia, had no
more than 6,000 men left of Reding’s old army, and was helpless to
interfere with St. Cyr who had some 20,000 men concentrated at
Vich.
The preparations for the siege therefore went on in the end of
April and the beginning of May without any hindrance, save from the
normal bickerings of the French outlying detachments with the local
somatenes, which never ceased. Around Vich matters were
particularly lively, for the whole population of the town and the
surrounding plains had gone up into the hills, where they wandered
miserably for three months, much hunted by French foraging parties,
which they occasionally succeeded in destroying. St. Cyr opened up
his communications with Reille by sending to him Lecchi’s Italian
division, which cut its way amid constant skirmishes along the banks
of the Ter to Gerona, and met the troops from the Ampurdam under
its walls. Reille had moved forth from Bascara on May 4, and on the
eighth expelled the Spanish outposts from all the villages round the
fortress, not without some lively skirmishing. He had brought up
some 10,000 infantry—including his own old division and all the
newly arrived Germans—with some 1,300 artillerymen and
engineers. Almost at the same moment arrived dispatches from
Paris, announcing that the Emperor, just before departing for the
Austrian war, had superseded both St. Cyr and Reille, being
discontented with their handling of affairs in Catalonia. It is
unfortunate that no statement in detail of his reasons appears in the
Correspondance[18]
, but it would seem that he thought that the
victories of Molins de Rey and Valls should have had greater results,
disapproved of St. Cyr’s retreat from in front of Tarragona, and
thought that Reille had shown great weakness in dealing with the
insurgents of the Ampurdam. He ignored the special difficulties of
the war in Catalonia, thinking that the 30,000 men of the 7th Corps
ought to have sufficed for its complete conquest. Indeed he showed
his conception of the general state of affairs by recommending St.
Cyr in March to undertake simultaneously the sieges of Gerona,
Tarragona, and Tortosa[19]
. The leaguer of one, and that the
smallest, of these places was destined to occupy the whole army of
Catalonia, when largely reinforced, for eight months. If it had been
cut up according to the imperial mandate, it is probable that at least
one of its sections would have been destroyed. St. Cyr wrote in his
memoirs that his master was jealous of him, and wished to see him
fail, even at the cost of wrecking the 7th Corps. This is of course
absurd; but there can be no doubt that the Emperor disliked his
lieutenant, all the more because of the long string of complaints,
and of demands for more men, money, and stores, which he was
now receiving week by week from Catalonia. He loved generals who
achieved the impossible, and hated grumblers and frondeurs, a class
to which St. Cyr, despite all his talents, undoubtedly belonged. It is
possible that Napoleon’s determination to replace him may have
been fostered by intrigues on the part of the officer to whom the 7th
Corps was now turned over. Marshal Augereau had served with great
credit in the old republican campaign in Catalonia during 1793 and
1794, imagined himself to have a profound knowledge of the
country, and was anxious to try his hand in it. It was many years
since he had been trusted with an independent command; both in
the wars of 1806-7 and in that of 1809 he had been lost in the ranks
of the Grand Army. His nomination to supersede St. Cyr was made
early in May, but on his way to the seat of war he was seized with a
fit of the gout, and was detained in bed at Perpignan for many
weeks. Thus his predecessor, though apprised of his disgrace, was
obliged to continue in command, and to commence the operations of
which the Marshal, as he well knew, would take all the credit. At the
same moment Reille was displaced by Verdier, the general who had
conducted the first unlucky siege of Saragossa—an experience which
seems to have made him very cautious when dealing with Spaniards
behind walls.
Lecchi’s division forced its way back to St. Cyr on May 18,
bringing him the intelligence of his supersession, but at the same
time apprising him that Augereau would not arrive as yet, and that
the duty of commencing the siege of Gerona would still fall to his lot.
At the same time Verdier sent letters urging that his 10,000 infantry
formed too small a force to surround such a large fortress, and that
he must ask for reinforcements from the covering army. If they were
denied him, he should refuse to begin the siege, throwing the
responsibility for this disobedience of the Emperor’s commands on
his superior: he had reported the situation to Paris. St. Cyr was
incensed at the tone of this dispatch[20]
, above all at the fact that
Verdier was appealing straight to the Emperor, instead of
corresponding through his hierarchical superior, according to the
rules of military etiquette. But he saw that Verdier had a good case,
and he had just learnt that Blake had turned off against Aragon, so
that no trouble from that quarter need be feared. Accordingly he,
very grudgingly, sent back Lecchi’s division to Gerona. It was the
worst that he possessed, being composed of no more than four
Neapolitan and three Italian battalions, with a strength of little over
3,000 bayonets[21]
. He added to it a regiment of Italian light horse,
several of his own batteries, and nearly all the engineers and
sappers of his corps, so that the total reinforcement sent to Verdier
consisted of more than 4,000 men.
Having received these succours, which brought up his total force
to 14,000 infantry and cavalry, and 2,200 artillerymen, sappers and
engineers, Verdier commenced on May 24 his operations against
Gerona: on that day Lecchi’s division took its post in the plain of
Salt, on the west of the town, while the French and Westphalian
divisions were already close to the place on its eastern and northern
sides. The head quarters and the French brigades of Joba and
Guillot lay by Sarria and the bridge of Pont-Mayor, where the
magazines were established, while the Germans had been sent up
on to the heights east of the fortress and held the plateaux of
Campdura, San Medir, and Domeny. The rocky southern side of
Gerona, in the direction of the gorge of the Oña, was not yet
properly invested.
Something has already been said, in an earlier volume of this
work, concerning the situation of Gerona, when its two earlier sieges
by Duhesme were narrated[22]
. It must suffice to repeat here that the
town is built on the steep down-slope of two lofty heights, with the
river Oña at its foot: the stream is crossed by two bridges, but is
fordable everywhere save in times of spate. Beyond it lies the
suburb of the Mercadal, surrounded by fortifications which form an
integral part of the defences of the city. The river Ter, coming from
the west, joins the Oña at the north side of the Mercadal and
washes the extreme north-western corner of the walls of the city
proper. The two heights upon whose lower slopes Gerona is built are
separated from each other by a deep ravine, called the Galligan,
down which run an intermittent watercourse and a road, the only
one by which approach to the city from the east is possible. The
northern height is crowned by the strong fort of Monjuich, the most
formidable part of the city defences, with its three outlying redoubts
called San Narciso, San Luis and San Daniel. The crest of the
southern height is covered in a similar fashion by the three forts of
the Capuchins, Queen Anne, and the Constable, with the Calvary
redoubt lower down the slope above the Galligan, facing San Daniel
on the other side of the ravine. Two other small fortifications, the
redoubts of the ‘Chapter’ and the ‘City,’ cover the path which leads
down from the forts to Gerona. Neither the Monjuich nor the
Capuchin heights are isolated hills; each is the end of a spur running
down from the higher mountains. But while the southern summit
rises high above the hilly reach which joins it to the mountain of
Nuestra Señora de los Angeles, the northern summit (where lies
Monjuich) is at the end of a plateau extending far to the north. The
Capuchin heights, therefore, can only be attacked uphill, while
Monjuich can be assailed from ground of a level little inferior to
itself. But except on this point both heights are very strong, their
slopes being in many places absolutely precipitous, especially
towards the Galligan, and everywhere steep. Nevertheless there are
winding paths leading up both, from Sarria and Pont-Mayor in the
case of Monjuich, from Casa de Selva and other villages towards the
east and the sea in the case of the Capuchin heights. All the ground
is bare rock, with no superincumbent soil.
All the fortifications were somewhat antiquated in type, nothing
having been done to modernize the defences since the war of the
Spanish Succession[23]
. Ferdinand VI and Charles III had neglected
Gerona in favour of the new fortress of Figueras, nearer to the
frontier, on which large sums had been expended—for the benefit of
the French who seized it by treachery in 1808, and were now using
it as their base of operations. The actual wall of enceinte of the city
was mediaeval—a plain rampart twenty-five feet high, too narrow for
artillery and set thickly with small towers; only at its two ends, on
the Oña and the Ter, two bastions (called those of La Merced and
Santa Maria) had been inserted, and properly armed. This weakness
of the walls went for little so long as Monjuich, the Capuchins, and
the other forts held firm, since the enemy could only approach the
town-enceinte at its two ends, where the bastions lay. Far more
dangerous was the feebleness of the Mercadal, whose ramparts
formed the southern section of the exterior defences of the place.
Its circuit had five plain bastions, but no demi-lunes or other outer
defences, no covered way nor counterscarp: its profile, only some
eighteen or twenty feet high, was visible, across the flat ground
which surrounds it, from the foot to the summit of the wall, for want
of ditch or glacis. The ground leading up to it was favourable for
siege approaches, since the soil was soft and easy to dig, and was
seamed with hollow roads and stone walls, giving much cover to an
assailant. Aware of the defects of the fortifications of the Mercadal,
the Spaniards had prepared a line of defence behind it, along the
further bank of the Oña. They had made the river-front of the city
proper defensible to a certain extent, by building up the doors and
windows of all the houses which abut upon the water, mining the
two bridges, and fixing a stockade and entanglements in the bed of
the Oña, along the considerable space, where it is fordable in dry
weather[24]
. They had indeed repaired the whole circuit of the
defences since Duhesme’s sieges of 1808, having cleared out the
ditches of Monjuich and of the bastions of La Merced and Santa
Maria, walled up many posterns, and repaired with new and solid
masonry all the parts of the walls that had been dilapidated at the
moment of the first siege. They had also pulled down many isolated
houses outside the walls, and demolished the nearer half of the
suburban village of Pedret, which lies (most inconveniently for the
defence) along the bank of the Ter between the water and the
slopes of Monjuich.
All these precautions must be put to the credit of the governor,
Mariano Alvarez de Castro, a man to be mentioned with all honour
and respect, and probably the best soldier that Spain produced
during the whole Peninsular War. He was a veteran of the
Revolutionary and Portuguese wars, and had a good reputation, but
no special credit for military science, down to the moment when he
was put to the test. He had been the officer in charge of the castle
of Barcelona on the occasion when it was seized by Duhesme in
March 1808: his spirit had been deeply wounded by that vile piece of
treachery, and he had at once adhered to the national cause. Since
then he had been serving in the Ampurdam against Reille, till the
moment when he was appointed governor of Gerona. Alvarez is
described by those who served under him as a severe, taciturn man
of a puritan cast of mind. ‘I should call him,’ wrote one of his
brigadiers, ‘an officer without the true military talents, but with an
extreme confidence in Providence—almost, one might say, a believer
in miracles. His soul was great, capable of every sacrifice, full of
admirable constancy; but I must confess that his heroism always
seemed to me that of a Christian martyr rather than of a
professional soldier[25]
.’ General Fournas, who wrote this somewhat
depreciatory sketch of his chief, was one of those who signed the
capitulation while Alvarez was moaning no quiero rendirme on his
sick-bed, so that his judgement is hardly to be taken as
unprejudiced; but his words point the impression which the governor
left on his subordinates. The details of his defence sufficiently show
that he was a skilful and resourceful as well as an obstinate general.
His minute care to utilize every possible means of defence prove that
he was no mere waiter on miracles. That he was a very devout
practising Catholic is evident from some of his doings; at the
opening of the siege a great religious ceremony was held, at which
the local patron saint, Narcissus, was declared captain of the city
and presented with a gold-hilted sword. The levy en masse of the
citizens was called ‘the Crusade,’ and their badge was the red cross.
The ideas of religion and patriotism were so closely intertwined that
to the lay companies of this force were afterwards added two clerical
companies, one composed of monks and friars, the other of secular
priests: about 200 of these ecclesiastics were under arms[26]
. Even
the women were organized in squads for the transport of wounded,
the care of the hospitals, and the carrying of provisions to the
soldiery on the walls: about 300 served, under the command of
Donna Lucia Fitzgerald and Donna Maria Angela Bibern, wives of two
officers of the regiment of Ultonia. Five of this ‘company of St.
Barbara’ were killed and eleven wounded during the siege.
The garrison at the moment of Verdier’s first attack consisted of
about 5,700 men, not including the irregulars of the Crusade. There
were seven battalions of the old army, belonging to the regiments of
Ultonia[27]
, Borbon, and Voluntarios de Barcelona, with three
battalions of miqueletes, two local corps, 1st and 2nd of Gerona, and
the 1st of Vich. Of cavalry there was a single squadron, newly levied,
the ‘escuadron de San Narciso.’ Of artillery there were but 278 men,
a wholly insufficient number: the officers of that arm were given 370
more to train, partly miqueletes of the 2nd Gerona battalion, partly
sailors having some small experience of gunnery. It was difficult to
make proper use of the great store of cannon in the fortress, when
more than half the troops allotted to them had never before seen,
much less served, a heavy gun of position. To the above 5,700 men
of all arms must be added about 1,100 irregulars of the ‘Crusade’—
seven lay and two clerical companies of fusiliers and two more of
artificers. But these were set to guard almost unapproachable parts
of the wall, or held in reserve: most of the stress fell upon the
organized troops. The defence was altogether conducted on
scientific principles, and had nothing in common with that of
Saragossa. Here the irregulars formed only a small fraction of the
garrison[28]
, and were never hurled in senseless fury against the
French batteries, but used carefully and cautiously as an auxiliary
force, capable of setting free some part of the trained men for
service on the more important points of the enceinte[29]
.
For the first two months of the siege Alvarez received no help
whatever from without: in May the central government of Catalonia
had been left in a perfectly paralysed condition, when Blake went off
himself and took with him the best of the regular troops, in order to
engage in the campaign of Alcañiz and Maria. Coupigny, the interim
commander at Tarragona, had only 6,000 organized men, and he
and the Catalan provincial junta were during that month much
engrossed with an enterprise which distracted them from the needs
of Gerona. A wide-spread conspiracy had been formed within the
walls of Barcelona, with the object of rising against the garrison in
St. Cyr’s absence. A secret committee of priests, merchants, and
retired officers had collected all the arms in the city, smuggled in
many muskets from without, and enlisted several thousand persons
in a grand design for an outbreak and a sort of ‘Sicilian Vespers’
fixed—after two postponements—for the 11th of May. They opened
communication with Coupigny and with the captains of the British
frigates blockading the port. The one was to bring his troops to the
gates, the others to deliver an attack on the port, upon the
appointed night. No Spaniard betrayed the plot, though 6,000
citizens are said to have been in the secret, but it was frustrated by
two foreigners. Conscious that the town could not be freed if the
citadel of Monjuich was retained by the French, the conspirators
sounded two Italian officers named Captain Dottori, fort adjutant of
Monjuich, and Captain Provana, who was known to be discontented
and thought to be corruptible. They offered them an immense bribe
—1,000,000 dollars, it is said—to betray the postern of Monjuich to
the troops of Coupigny, who were to be ready in the ditch at
midnight. But they had mistaken their men: the officers conferred
with Duhesme, and consented to act as agents provocateurs: they
pretended to join the conspiracy, were introduced to and had
interviews with the chiefs, and informed the governor. On the
morning before the appointed date many of the leaders were
arrested. Duhesme placed guards in every street, and proclaimed
that he knew all. The citizens remained quiet in their despair, the
chiefs who had not been seized fled, and the troops on the Llobregat
retired to Tarragona. Duhesme hanged his captives, two priests
named Gallifa and Pou, a young merchant named Massana, Navarro
an old soldier, and four others. ‘They went to the gallows,’ says
Vacani, an eye-witness, ‘with pride, convinced every one of them
that they had done the duty of good citizens in behalf of king,
country, and religion[30]
.’
Engrossed in this plot, the official chiefs of Catalonia half forgot
Gerona, and did nothing to help Alvarez till long after the siege had
begun. The only assistance that he received from without was that
the miqueletes and somatenes of the Ampurdam and the mountain
region above Hostalrich were always skirmishing with Verdier’s
outposts, and once or twice cut off his convoys of munitions on their
way from Figueras to the front.
The French engineers were somewhat at variance as to the right
way to deal with Gerona. There were two obvious alternatives. An
attack on the weak front of the Mercadal was certain to succeed: the
ground before the walls was suitable for trenches, and the
fortifications were trifling. But when a lodgement had been made in
this quarter of the town it would be necessary to work forward,
among the narrow lanes and barricades, to the Oña, and then to
cross that river in order to continue similar operations through the
streets of Gerona. Even when the city had been subdued, the
garrison might still hold out in the formidable works on the Monjuich
and Capuchin heights. The reduction of the Mercadal and the city,
moreover, would have to be carried out under a continuous plunging
fire from the forts above, which overlooked the whole place. This
danger was especially insisted upon by some of the engineer
officers, who declared that it would be impossible for the troops to
work their way forward over ground so exposed. As a matter of fact
it was proved, after the siege was over and the forts had been
examined by the captors, that this fear had been exaggerated; the
angle of fire was such that large sections of the town were in no way
commanded from the heights, and the streets could not have been
searched in the fashion that was imagined. But this, obvious in
December, could not have been known in May[31]
. The second
alternative was to commence the attack on Gerona not from the
easiest but from the most difficult side, by battering the lofty fort of
Monjuich from the high plateau beside it. The defences here were
very formidable: the ground was bare exposed rock: but if Monjuich
were once captured it was calculated that the town must surrender,
as it was completely overlooked by the fort, and had no further
protection save its antiquated mediaeval wall. The deduction that it
would be cheaper in the end to begin with the difficult task of taking
Monjuich, rather than the easier operations against the Mercadal,
seemed plausible: its fault was that it presupposed that Alvarez and
his garrison would behave according to the accepted rules of
siegecraft, and yield when their situation became hopeless. But in
dealing with Spanish garrisons the rules of military logic did not
always act. Alvarez essayed the impossible, and held out behind his
defective defences for four months after Monjuich fell. The loss of
men and time that he thereby inflicted on the French was certainly
no less than that which would have been suffered if the besiegers
had begun with the Mercadal, and worked upwards by incessant
street fighting towards the forts on the height. But it is hard to say
that Verdier erred: he did not know his adversary, and he did know,
from his experiences at Saragossa, what street fighting meant.
It may be added that Verdier’s views were accepted by the
engineer-general, Sanson, who had been specially sent from France
by the Emperor, to give his opinion on the best mode of procedure.
The document which Verdier, Sanson, and Taviel (the commanding
artillery officer of the 7th Corps) sent to Paris, to justify their choice
of the upper point of attack, lays stress mainly on the impossibility of
advancing from the Mercadal under the fire of the upper forts[32]
. But
there were other reasons for selecting Monjuich as the point of
attack. It lay far nearer to the road to France and the central siege-
dépôts beside Sarria and the Pont Mayor. The approaches would be
over highly defensible ground where, if a disaster occurred, the
defeated assailant could easily recover himself and oppose a strong
front to the enemy. The shortness of the front was suitable for an
army of the moderate strength of 14,000 men, which had to deal
with a fortress whose perimeter, allowing for outlying forts and
inaccessible precipices, was some six miles. Moreover, the ground in
front of the Mercadal had the serious inconvenience of being liable
to inundation; summer spates on the Ter and Oña are rare, but
occur from time to time; and there was the bare chance that when
the trenches had been opened all might be swept away by the
rivers[33]
.
Verdier’s opinion was arrived at after mature reflection: the
French had appeared in front of Gerona on May 8: the outlying
villages on the east had been occupied between the twelfth and
eighteenth: Lecchi’s Italians had closed the western exits by
occupying the plain of Salt on the twenty-fourth: the inner posts of
observation of the Spaniards had been cleared off when, on May 30,
the Italians seized the suburban village of Santa Eugenia, and on
June 1 the Germans took possession of the mountain of Nuestra
Señora de los Angeles. But it was only on June 6 that the besiegers
broke ground, and commenced their trenches and batteries on the
plateau of Monjuich. It was necessary to make a beginning by
subduing the outer defences of the fort, the towers or redoubts of
San Luis, San Narciso, and San Daniel: two batteries of 24-pounders
were constructed against them, while a third battery of mortars on
the ‘Green Mound’ by the Casa den Roca on the west bank of the
Ter, was to play upon the north end of the town: Verdier hoped that
the bombardment would break the spirit of the citizens—little
knowing the obstinate people with whom he had to deal. Five
thousand bombs thrown into the place in June and July produced no
effect whatever. More batteries on the heights were thrown up upon
the 13th and 15th of June, while on the former day, to distract the
attention of the Spaniards, Lecchi’s division, in the plain below, was
ordered to open a false attack upon the Mercadal. This had good
effect as a diversion, since Alvarez had expected an assault in this
quarter, and the long line of trenches thrown up by the Italians in
front of Santa Eugenia attracted much of his attention. Three days of
battering greatly damaged San Luis and San Narciso, which were no
more than round towers of masonry with ditches cut in the rock, and
only two or three guns apiece. The French also took possession on
the night of the fourteenth and fifteenth of the remains of the half-
destroyed suburb of Pedret, between Monjuich and the Ter, as if
about to establish themselves in a position from which they could
attack the low-lying north gate of the town and the bastion of Santa
Maria.
Hitherto the defence had seemed a little passive, but at dawn on
the morning of the seventeenth Alvarez delivered the first of the
many furious sallies which he made against the siege lines. A
battalion of Ultonia rushed suddenly down-hill out of Monjuich and
drove the French, who were taken completely by surprise, out of the
ruins of Pedret. Aided by a smaller detachment, including the
artificers of the Crusade, who came out of the Santa Maria gate,
they destroyed all the works and lodgements of the besiegers in the
suburb, and held it till they were driven out by two French and one
Westphalian battalion sent up from Verdier’s reserves. The Spaniards
were forced back into the town, but retired in good order, contented
to have undone three days of the besiegers’ labour. They had lost
155 men, the French 128, in this sharp skirmish.
Two days later the towers of San Luis and San Narciso, which had
been reduced to shapeless heaps of stone, were carried by assault,
with a loss to the French of only 78 men; but an attempt to carry
San Daniel by the same rush was beaten off, this redoubt being still
in a tenable state. Its gorge, however, was completely commanded
from the ruins of San Luis, and access to or exit from it was
rendered so dangerous that Alvarez withdrew its garrison on the
next night. The possession of these three outworks brought the
French close up to Monjuich, which they could now attack from
ground which was favourable in every respect, save that it was bare
rock lacking soil. It was impossible to excavate in it, and all advances
had to be made by building trenches (if the word is not a misnomer
in this case) of sandbags and loose stones on the surface of the
ground. The men working at the end of the sap were therefore
completely exposed, and the work could only proceed at a great
expense of life. Nevertheless the preparations advanced rapidly, and
on the night of July 2 an enormous battery of sandbags (called the
Batterie Impériale) was thrown up at a distance of only four hundred
yards from Monjuich. Next morning it opened on the fort with twenty
16- and 24-pounders, and soon established a superiority over the
fire of the defence. Several Spanish pieces were dismounted, others
had to be removed because it was too deadly to serve them. But a
steady fire was returned against the besiegers from the Constable
and Calvary forts, on the other side of the Galligan ravine.
Nevertheless Monjuich began to crumble, and it looked as if the end
of the siege were already approaching. On July 3 there was a breach
thirty-five feet broad in the fort’s north-eastern bastion, and the
Spanish flag which floated over it was thrown down into the ditch by
a chance shot. A young officer named Montorro climbed down,
brought it up, and nailed it to a new flagstaff under the fire of
twenty guns. Meanwhile long stretches of the parapet of Monjuich
were ruined, the ditch was half-filled with débris, and the garrison
could only protect themselves by hasty erections of gabions and
sandbags, placed where the crest of the masonry had stood.
By this time St. Cyr and the covering army had abandoned the
position in the plain of Vich which they had so long occupied. The
general had, as it seems, convinced himself at last that Blake, who
was still engaged in his unlucky Aragonese campaign, was not likely
to appear. He therefore moved nearer to Gerona, in order to repress
the efforts of the local somatenes, who were giving much trouble to
Verdier’s communications. On June 20 he established his head
quarters at Caldas de Malavella, some nine miles to the south-east
of Gerona. That same evening one of his Italian brigades intercepted
and captured a convoy of 1,200 oxen which the Governor of
Hostalrich was trying to introduce into the beleaguered city along
one of the mountain-paths which lead to the Capuchin heights from
the coast. St. Cyr strung out his 14,000 men in a line from San Feliu
de Guixols on the sea to the upper Ter, in a semicircle which covered
all the approaches to Gerona saving those from the Ampurdam. He
visited Verdier’s camp, inspected the siege operations, and
expressed his opinion that an attack on the Mercadal front would
have been preferable to that which had been actually chosen. But he
washed his hands of all responsibility, told Verdier that, since he had
chosen to correspond directly with Paris, he must take all the praise
or blame resulting from his choice, and refused to countermand or
to alter any of his subordinate’s dispositions. On July 2 however he
sent, with some lack of logic, a summons of his own to Alvarez,
inviting him to surrender on account of the desperate state of his
defences: this he did without informing Verdier of his move. The
Governor returned an indignant negative, and Verdier wrote in great
wrath to complain that if the siege was his affair, as he had just been
told, it was monstrous that his commander should correspond with
the garrison without his knowledge[34]
. The two generals were left on
even worse terms than before. St. Cyr, however, gave real assistance
to the siege operations at this time by storming, on July 5, the little
fortified harbour-town of Palamos, which lies on the point of the sea-
coast nearest to Gerona, and had been hitherto used by the
miqueletes as a base from which they communicated by night with
the fortress, and at the same time kept in touch with Tarragona and
the English ships of the blockading squadron.
On the night of the 4th and 5th of July the defences of Monjuich
appeared in such a ruinous condition that Commandant Fleury, the
engineer officer in charge of the advanced parallel, took the
extraordinary and unjustifiable step of assaulting them at 10 p.m.
with the troops—two companies only—which lay under his orders,
trusting that the whole of the guards of the trenches would follow if
he made a lodgement. This presumptuous attack, made contrary to
all the rules of military subordination, was beaten off with a loss of
forty men. Its failure made Verdier determine to give the fort three
days more of continuous bombardment, before attempting to storm
it: the old batteries continued their fire, a new one was added to
enfilade the north-western bastion, and cover was contrived at
several points to shelter the troops which were to deliver the assault,
till the actual moment of the storm arrived[35]
. But three hundred
yards of exposed ground still separated the front trenches from the
breach—a distance far too great according to the rules of siegecraft.
The Spaniards meanwhile, finding it impossible under such a fire to
block the breach, which was now broad enough for fifty men
abreast[36]
, threw up two walls of gabions on each side of it, sank a
ditch filled with chevaux-de-frise in front of it, and loopholed some
interior buildings of the fort, which bore upon its reverse side.
Monjuich, however, looked in a miserable state when, just before
sunrise on July 7, Verdier launched his columns of assault upon it.
He had collected for the purpose the grenadier and voltigeur
companies of each of the twenty French, German, and Italian
battalions of the besieging army, about 2,500 men in all[37]
. They
were divided into two columns, the larger of which went straight at
the breach, while the smaller, which was furnished with ladders, was
directed to escalade the left face of the demi-lune which covers the
northern front of Monjuich. The troops passed with no great loss
over the open space which divided them from the work, as its guns
had all been silenced, and the fire from the more distant forts was
ineffective in the dusk. But when they got within close musketry
range they began to fall fast; the head of the main column, which
was composed of some sapper companies and the Italian Velites of
the Guard, got up on to the face of the breach, but could never
break in. Every officer or man who reached the cutting and its
chevaux-de-frise was shot down; the concentric fire of the defenders
so swept the opening that nothing could live there. Meanwhile the
rear of the column was brought to a stand, partly in, partly outside,
the ditch. The Spaniards kept playing upon it with musketry and two
or three small 2- and 4-pounders, which had been kept under cover
and reserved for that purpose, firing canister into it at a distance of
twenty or thirty yards. Flesh and blood could not bear this for long,
and the whole mass broke and went to the rear. Verdier, who had
come out to the Batterie Impériale to view the assault, had the men
rallied and sent forward a second time: the head of the column
again reached the breach, and again withered away: the supporting
mass gave way at once, and fell back much more rapidly than on the
first assault. Yet the General, most unwisely, insisted on a third
attack, which, made feebly and without conviction, by men who
knew that they were beaten, only served to increase the casualty
list. Meanwhile the escalade of the demi-lune by the smaller column
had been repelled with ease: the assailants barely succeeded in
crossing the ditch and planting a few ladders against the scarp: no
one survived who tried to mount them, and the troops drew off.
This bloody repulse cost the French 1,079 casualties, including
seventy-seven officers killed or wounded—much more than a third of
the troops engaged. It is clear, therefore, that it was not courage
which had been lacking: nor could it be said that the enemy’s
artillery fire had not been subdued, nor that the breach was
insufficient, nor that the 300 yards of open ground crossed by the
column had been a fatal obstacle; indeed, they had been passed
with little loss. The mistake of Verdier had been that he attacked
before the garrison was demoralized—the same error made by the
English at Badajoz in 1811 and at San Sebastian in 1813. A broad
breach by itself does not necessarily make a place untenable, if the
spirit of the defenders is high, and if they are prepared with all the
resources of the military art for resisting the stormers, as were the
Geronese on July 7-8. The garrison lost, it may be remarked, only
123 men, out of a strength of 787 present in the fort that morning.
The casualty list, however, was somewhat increased by the
accidental explosion, apparently by a careless gunner, of the
magazine of the tower of San Juan, alongside of the Galligan, which
was destroyed with its little garrison of twenty-five men.
The repulse of the assault of Monjuich thoroughly demoralized
the besieging army: the resistance of the Spaniards had been so
fierce, the loss they had inflicted so heavy, that Verdier’s motley
collection of French, German, Lombard, and Neapolitan regiments
lost heart and confidence. Their low spirits were made manifest by
the simultaneous outbreak of desertion and disease, the two
inevitable marks of a decaying morale. All through the second half of
July and August the hospitals grew gradually fuller, not only from
sunstroke cases (which were frequent on the bare, hot, rocky
ground of the heights), but from dysentery and malaria. The banks
of the Ter always possessed a reputation for epidemics—twice in
earlier centuries a French army had perished before the walls of
Gerona by plagues, which the citizens piously attributed to their
patron, San Narciso. It was mainly because he realized the
depression of his troops that Verdier refrained from any more
assaults, and went on from July 9 to August 4 battering Monjuich
incessantly, while he cautiously pushed forward his trenches, till they
actually reached the ditch of the demi-lune which covers the
northern front of the fort. The garrison was absolutely overwhelmed
by the incessant bombardment, which destroyed every piece of
upstanding masonry, and prevented them from rebuilding anything
that was demolished. They were forced to lurk in the casemates,
and to burrow for shelter in the débris which filled the interior of the
work. Three large breaches had been made at various points, yet
Verdier would never risk another assault, till on August 4 his
approaches actually crowned the lip of the ditch of the demi-lune,
and his sappers had blown in its counterscarp. The ruined little
outwork was then stormed with a loss of only forty men. This put
the French in the possession of good cover only a few yards from
the main body of the fort. Proceeding with the same caution as
before, they made their advances against Monjuich by mining: on
the night of the 8th–9th August no less than twenty-three mines
under the glacis of the fort were exploded simultaneously. This left a
gaping void in front of the original breach of July 7, and filled up the
ditch with débris for many yards on either side: part of the interior of
the fort was clearly visible from the besiegers’ trenches.
Only one resource for saving Monjuich remained to Alvarez—a
sortie for the expulsion of the enemy from their advanced works. It
was executed with great courage at midday on August 9, while at
the same time separate demonstrations to distract the enemy were
made at two other points. The column from Monjuich had
considerable success; it stormed two advanced batteries, spiked
their guns, and set fire to their gabions; the French were cleared out
of many of their trenches, but made head behind one of the rear
batteries, where they were joined by their reserves, who finally
thrust back the sallying force into the fort. The damage done,
though considerable, could be repaired in a day. Verdier gave orders
for the storm of the dilapidated fort on the night of August 11, and
borrowed a regiment from St. Cyr’s covering army to lead the
assault, being still very doubtful of the temper of his own troops. But
at six on the preceding afternoon an explosion was heard in
Monjuich, and great part of its battered walls flew up into the air.
The Spaniards had quietly evacuated it a few minutes before, after
preparing mines for its demolition. The French, when they entered,
found nothing but a shapeless mass of stones and eighteen disabled
cannon. The garrison had lost, in the sixty-five days of its defence,
962 men killed and wounded; the besiegers had, first and last,
suffered something like three times this loss.
While the bombardment of Monjuich was going on, the Spanish
generals outside the fortress had at last begun to make serious
efforts for its assistance. Not only had the somatenes redoubled
their activity against Verdier’s convoys, and several times succeeded
in destroying them or turning them back, but Coupigny had at last
begun to move, for he saw that since Blake’s rout at Belchite on
June 18 he, and he alone, possessed an organized body of troops on
this side of Spain, small though it was. Unable to face St. Cyr in the
field, he tried at least to throw succours into Gerona by the
mountain paths from the south, if he could do no more. The first
attempt was disastrous: three battalions started from Hostalrich
under an English adventurer, Ralph Marshall, whom Alvarez had
suggested for the command of this expedition. They evaded the first
line of the covering army, but at Castellar, on July 10, ran into the
very centre of Pino’s division, which had concentrated from all sides
for their destruction. Marshall escaped into Gerona with no more
than twelve men: 40 officers and 878 rank and file laid down their
arms; the rest of the column, some 600 or 700 men, evaded
surrender by dispersion[38]
.
Equally disastrous, though on a smaller scale, was another
attempt made on August 4 by a party of 300 miqueletes to enter
Gerona: they eluded St. Cyr, but on arriving at the entry of the
Galligan, close under the forts, made the unfortunate mistake of
entering the convent of San Daniel, which the garrison had been
compelled to evacuate a few days before. It was now in the French
lines, and the Catalans were all taken prisoners. It was not till
August 17, six days after the fall of Monjuich, that Alvarez obtained
his first feeble reinforcement: the miquelete battalion of Cervera,
with a draft for that of Vich already in the garrison, altogether 800
bayonets, got into the city on the west side, by eluding Lecchi’s
Italians in the plain and fording the Ter. They were much needed, for
Alvarez was complaining to the Catalan Junta that he had now only
1,500 able-bodied men left of his original 5,000[39]
.
Verdier had written to his master, after the capture of Monjuich,
to announce that Gerona must infallibly surrender within eight or ten
days[40]
, now that it had nothing but an antiquated mediaeval wall to
oppose to his cannon. So far, however, was he from being a true
prophet that, as a matter of fact, the second and longer episode of
the siege, which was to be protracted far into the winter, had only
just begun.
SECTION XVII: CHAPTER III
THE FALL OF GERONA. AUGUST–DECEMBER, 1809
When Monjuich had been evacuated, the position of Gerona was
undoubtedly perilous: of the two mountain summits which command
the city one was now entirely in the hands of the French; for not
only the great fort itself but several of the smaller works above the
ravine of the Galligan—such as the fortified convent of San Daniel
and the ruined tower of San Juan—had been lost. The front exposed
to attack now consisted of the northern section of the old city wall,
from the bastion of Santa Maria at the water’s edge, to the tower of
La Gironella, which forms the north-eastern angle of the place, and
lies further up the slope of the Capuchin heights than any other
portion of the enceinte. The space between these two points was
simply covered by a mediaeval wall set with small round towers:
neither the towers nor the curtain between them had been built to
hold artillery. Indeed the only spots on this front where guns had
been placed were (1) the comparatively modern bastion of Santa
Maria, (2) a work erected under and about the Gironella, and called
the ‘Redoubt of the Germans,’ and (3, 4) two parts of the wall called
the platforms[41]
of San Pedro and San Cristobal, which had been
widened till they could carry a few heavy guns. On the rest of the
enceinte, owing to its narrowness, nothing but wall-pieces and two-
pounders could be mounted. The parts of the curtain most exposed
to attack were the sections named Santa Lucia, San Pedro, San
Cristobal, and Las Sarracinas, from churches or quarters which lay
close behind them. With nothing but an antiquated wall, seven to
nine feet thick, thirty feet high, and destitute of a ditch, it seemed
that this side of Gerona was doomed to destruction within a few
days.
But there were points in the position which rendered the attack
more difficult than might have been expected. The first was that any
approaches directed against this front would be exposed to a
flanking fire from the forts on the Capuchin heights, especially from
the Calvary and Chapter redoubts. The second was that the greater
part of the weak sections of the wall were within a re-entering
angle; for the tower of Santa Lucia and the ‘Redoubt of the
Germans’ by the Gironella project, and the curtains between them
are in a receding sweep of the enceinte. Attacks on these ill-fortified
sections would be outflanked and enfiladed by the two stronger
works. The only exposed part of the curtain was that called Santa
Lucia, running from the tower of that name down to the bastion of
Santa Maria. Lastly, the parallels which the French might construct
from their base on Monjuich would have to be built on a down slope,
overlooked by loftier ground, and when they reached the foot of the
walls they would be in a sort of gulley or bottom, into which the
defenders of the city could look down from above. The only point
from which the north end of Gerona could be approached from flat
ground and without disadvantages of slope, is the short front of less
than 200 yards breadth between the foot of Monjuich and the bank
of the Ter. Here, in the ruins of the suburb of Pedret, there was
plenty of cover, a soil easy to work, and a level terrain as far as the
foot of the Santa Maria bastion. The engineers of the besieging army
selected three sections of wall as their objective. The first was the
‘Redoubt of the Germans’ and the tower of La Gironella, the highest
and most commanding works in this part of the enceinte: once
established in these, they could overlook and dominate the whole
city. The other points of attack were chosen for the opposite reason
—because they were intrinsically weak in themselves, not because
they were important or dominating parts of the defences. The
curtain of Santa Lucia in particular seemed to invite attack, as being
in a salient angle, unprotected by flanking fire, and destitute of any
artillery of its own.
Verdier, therefore, on the advice of his engineers, set to work to
attack these points of the enceinte between La Gironella and Santa
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookultra.com

More Related Content

PDF
Perl intro
PDF
PerlIntro
PDF
PerlIntro
PDF
Perl%20Tutorial.!Picking%20Up%20Perl
PDF
Perl%20Tutorial.!Picking%20Up%20Perl
PPTX
Bioinformatics v2014 wim_vancriekinge
PPTX
programming language interface i.pptx
Perl intro
PerlIntro
PerlIntro
Perl%20Tutorial.!Picking%20Up%20Perl
Perl%20Tutorial.!Picking%20Up%20Perl
Bioinformatics v2014 wim_vancriekinge
programming language interface i.pptx

Similar to Programming the Network with Perl 1st Edition Paul Barry (20)

PDF
Mastering Perl Second Edition Brian D Foy
PDF
Java Network Programming Fourth Edition Elliotte Rusty Harold
PDF
Perl-crash-course
PDF
Perl-crash-course
PDF
Perl-crash-course
PDF
Perl-crash-course
PPTX
Perl bhargav
PDF
Java Network Programming Fourth Edition Harold Elliotte
PDF
Java Network Programming Fourth Edition Elliotte Rusty Harold
DOCX
Ravi software faculty
PPTX
Bioinformatics p1-perl-introduction v2013
PPS
Web Development in Perl
PPTX
Perl slid
DOC
Perl web programming
PDF
Download ebooks file Practical mod_perl 1st Edition Stas Bekman all chapters
PPTX
Perl basics for pentesters part 2
PDF
topic_perlcgi
PDF
topic_perlcgi
PDF
Bgnet a4 2
PDF
Practical mod_perl 1st Edition Stas Bekman
Mastering Perl Second Edition Brian D Foy
Java Network Programming Fourth Edition Elliotte Rusty Harold
Perl-crash-course
Perl-crash-course
Perl-crash-course
Perl-crash-course
Perl bhargav
Java Network Programming Fourth Edition Harold Elliotte
Java Network Programming Fourth Edition Elliotte Rusty Harold
Ravi software faculty
Bioinformatics p1-perl-introduction v2013
Web Development in Perl
Perl slid
Perl web programming
Download ebooks file Practical mod_perl 1st Edition Stas Bekman all chapters
Perl basics for pentesters part 2
topic_perlcgi
topic_perlcgi
Bgnet a4 2
Practical mod_perl 1st Edition Stas Bekman
Ad

Recently uploaded (20)

PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Computing-Curriculum for Schools in Ghana
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
master seminar digital applications in india
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Cell Structure & Organelles in detailed.
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
102 student loan defaulters named and shamed – Is someone you know on the list?
A systematic review of self-coping strategies used by university students to ...
Computing-Curriculum for Schools in Ghana
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
VCE English Exam - Section C Student Revision Booklet
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
STATICS OF THE RIGID BODIES Hibbelers.pdf
Complications of Minimal Access Surgery at WLH
master seminar digital applications in india
Abdominal Access Techniques with Prof. Dr. R K Mishra
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Final Presentation General Medicine 03-08-2024.pptx
GDM (1) (1).pptx small presentation for students
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Microbial diseases, their pathogenesis and prophylaxis
Cell Structure & Organelles in detailed.
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Ad

Programming the Network with Perl 1st Edition Paul Barry

  • 1. Visit https://ebookultra.com to download the full version and explore more ebooks Programming the Network with Perl 1st Edition Paul Barry _____ Click the link below to download _____ https://ebookultra.com/download/programming-the- network-with-perl-1st-edition-paul-barry/ Explore and download more ebooks at ebookultra.com
  • 2. Here are some suggested products you might be interested in. Click the link to download Graphics Programming with Perl 1st Edition Martien Verbruggen https://ebookultra.com/download/graphics-programming-with-perl-1st- edition-martien-verbruggen/ Modern Perl Programming 1st Edition Michael Saltzman https://ebookultra.com/download/modern-perl-programming-1st-edition- michael-saltzman/ Beginning Programming with Java For Dummies 4th Edition Barry Burd https://ebookultra.com/download/beginning-programming-with-java-for- dummies-4th-edition-barry-burd/ Beginning Programming with Java for Dummies 5th Edition Barry Burd https://ebookultra.com/download/beginning-programming-with-java-for- dummies-5th-edition-barry-burd/
  • 3. Advanced Perl Programming Second Edition Simon Cozens https://ebookultra.com/download/advanced-perl-programming-second- edition-simon-cozens/ Penetration Testing with Perl 1st Edition Berdeaux https://ebookultra.com/download/penetration-testing-with-perl-1st- edition-berdeaux/ HTML5 Programming with JavaScript For Dummies 1st Edition John Paul Mueller https://ebookultra.com/download/html5-programming-with-javascript-for- dummies-1st-edition-john-paul-mueller/ Windows sockets network programming 1st Edition Bob Quinn https://ebookultra.com/download/windows-sockets-network- programming-1st-edition-bob-quinn/ Beginning Programming with Python For Dummies 3rd Edition John Paul Mueller https://ebookultra.com/download/beginning-programming-with-python-for- dummies-3rd-edition-john-paul-mueller/
  • 5. Programming the Network with Perl 1st Edition Paul Barry Digital Instant Download Author(s): Paul Barry ISBN(s): 9780471486701, 0471486701 Edition: 1 File Details: PDF, 1.18 MB Language: english
  • 10. Paul Barry Institute of Technology, Carlow, Ireland
  • 11. Copyright ©2002 John Wiley & Sons Ltd Baffins Lane, Chichester, West Sussex PO19 1UD, England National 01243 779777 International (+44) 1243 779777 e-mail (for orders and customer service enquiries): cs-books@wiley.co.uk Visit our Home Page on http://www.wileyeurope.com or http://www.wiley.com All Rights Reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except under the terms of the Copyright, Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licensing Agency Ltd, 90 Tottenham Court Road, London, UK W1P 0LP, without the permission in writing of the Publisher with the exception of any material supplied specifically for the purpose of being entered and executed on a computer system for exclusive use by the purchaser of the publication. Neither the author nor John Wiley & Sons, Ltd accept any responsibility or liability for loss or damage occasioned to any person or property through using the material, instructions, methods or ideas contained herein, or acting or refraining from acting as a result of such use. The author and publisher expressly disclaim all implied warranties, including mer- chantability or fitness for any particular purpose. There will be no duty on the author or publisher to correct any errors or defects in the software. Designations used by companies to distinguish their products are often claimed as trade- marks. In all instances where John Wiley & Sons, Ltd is aware of a claim, the product names appear in capital or all capital letters. Readers, however, should contact the appropriate companies for more complete information regarding trademarks and registration Library of Congress Cataloging-in-Publication Data (applied for) British Library Cataloguing in Publication Data A catalogue record for this book is available from the British Library ISBN 0 471 48670 1 Typeset in 9.5/12.5pt Lucida Bright by T&T Productions Ltd, London. Printed and bound in Great Britain by Biddles Ltd, Guildford and Kings Lynn. This book is printed on acid-free paper responsibly manufactured from sustainable forestry in which at least two trees are planted for each one used for paper production.
  • 12. Dedicated to Deirdre, for continuing to put her ambitions on hold while I pursue mine.
  • 14. Contents Preface xiii 1 Meet Perl 1 1.1 Perl’s Default Behaviour 1 1.1.1 Our first Perl program 2 1.1.2 Perl’s default variable 3 1.1.3 The strange first line explained 3 1.2 Using Variables in Perl 4 1.2.1 One of something: scalars 5 1.2.2 A collection of somethings: arrays and lists 6 1.2.3 Hashes 8 1.2.4 References 9 1.2.5 Built-in variables 12 1.2.6 Scoping with local, my and our 12 1.3 Controlling Flow 13 1.3.1 if 13 1.3.2 The ternary conditional operator 14 1.3.3 while 15 1.3.4 for 15 1.3.5 unless 16 1.3.6 until 16 1.3.7 foreach 16 1.3.8 do 17 1.3.9 eval 17 1.3.10 Statement modifiers 18 1.4 Boolean in Perl 19 1.5 Perl Operators 20 1.6 Subroutines 21 1.6.1 Processing parameters 21 1.6.2 Returning results 22 1.6.3 I want an array 23 1.6.4 In-built subroutines 23 1.6.5 References to subroutines 26 1.7 Perl I/O 26 1.7.1 Variable interpolation 28 1.8 Packages, Modules and Objects 29 1.8.1 Modules 30 1.8.2 Objects 30 1.8.3 The joy of CPAN 31 1.9 More Perl 32 1.10 Where To From Here? 32
  • 15. viii Contents 1.11 Print Resources 32 1.12 Web Resources 33 2 Snooping 35 2.1 Thank You, Tim Potter 36 2.2 Preparing To Snoop 37 2.2.1 Installing NetPacket::* 37 2.2.2 Installing Net::Pcap 38 2.2.3 Installing Net::PcapUtils 39 2.2.4 Online documentation 39 2.2.5 Configuring your network interface 40 2.3 Building Low-Level Snooping Tools 41 2.3.1 loop = open + next 42 2.3.2 Optional parameters: loop and open 43 2.3.3 Optional parameters: the callback function 45 2.3.4 Ethernet Analysis 45 2.3.5 EtherSnooper (v0.01) 48 2.3.6 EtherSnooper (v0.02) 52 2.3.7 EtherSnooper (v0.03) 55 2.3.8 Displaying IP addresses 58 2.4 Snooping IP Datagrams 63 2.4.1 EtherSnooper (v0.05) 64 2.4.2 EtherSnooper (v0.06) 67 2.5 Transport Snoopers 69 2.5.1 Preparing to snoop UDP 70 2.5.2 Preparing to snoop TCP 70 2.5.3 The TCP and UDP gotcha! 71 2.5.4 Application traffic monitoring 75 2.5.5 EtherSnooper (v0.07) 81 2.6 The Network Debugger 83 2.6.1 Processing command-line parameters 85 2.6.2 Storing captured results 85 2.6.3 The NetDebug source code 86 2.7 Where To From Here? 95 2.8 Print Resources 95 2.9 Web Resources 96 3 Sockets 99 3.1 Clients and Servers 99 3.1.1 Client characteristics 100 3.1.2 Server characteristics 101 3.2 Transport Services 101 3.2.1 Unreliable transport 102 3.2.2 Reliable transport 103 3.3 Introducing the Perl Socket API 104 3.4 Socket Support Subroutines 105 3.4.1 inet_aton and inet_ntoa 105 3.4.2 Socket addresses 105 3.4.3 getservbyname and getservbyport 106 3.4.4 getprotobyname and getprotobynumber 106 3.4.5 gethostbyname and gethostbyaddr 107 3.5 Simple UDP Clients and Servers 108 3.5.1 Testing with localhost 108 3.5.2 The first UDP server 108 3.5.3 The first UDP client 111
  • 16. Contents ix 3.6 Genericity and Robustness 112 3.7 UDP Is Unreliable 116 3.7.1 No flow control 117 3.8 Sending and Receiving with UDP 118 3.9 Dealing with Deadlock 120 3.9.1 Specifying a time-out 121 3.9.2 Checking for data 123 3.9.3 Spawning a subprocess 125 3.10 TCP Clients and Servers 130 3.10.1 The first TCP server 131 3.10.2 The first TCP client 134 3.11 A Common TCP Gotcha 140 3.12 More TCP Socket Communication 143 3.12.1 The remote syntax checker server 144 3.12.2 The remote syntax checker client 147 3.13 The Concurrent Syntax Checker 150 3.14 Object-Oriented Sockets 153 3.14.1 IO::Socket 154 3.14.2 IO::Socket::INET 154 3.14.3 An object-oriented client and server 156 3.15 Where To From Here? 158 3.16 Print Resources 158 3.17 Web Resources 159 4 Protocols 161 4.1 Gotcha! 161 4.1.1 What’s the deal with newline? 162 4.2 Working with the Web 164 4.2.1 HTTP requests and responses 164 4.3 The World’s Worst Web Browser 165 4.3.1 Embedded graphics 168 4.3.2 A persistent wwwb 169 4.3.3 A better get_resource 172 4.4 HTTP Status Codes 174 4.5 It’s the Gisle and Graham Show! 178 4.5.1 Getting libwww-perl and libnet 179 4.6 The Library for WWW Access in Perl 180 4.6.1 The libwww-perl classes 181 4.7 The LWPwwwb Program 181 4.8 Doing More with LWPwwwb 184 4.8.1 Parsing HTML 185 4.8.2 Some parsewwwb examples 187 4.8.3 The HTML::Parser examples 189 4.9 Building a Custom Web Server 190 4.9.1 The custom Web server source code 190 4.9.2 The custom Web server in action 196 4.10 The libnet Library 197 4.10.1 Working with Usenet 198 4.10.2 The news reading source code 199 4.11 Email Enabling simplehttpd 205 4.11.1 The simple mail transfer protocol 205 4.11.2 The Net::SMTP module 210 4.11.3 Creating simplehttp2d 211
  • 17. x Contents 4.12 Other Networking Add-On Modules 213 4.12.1 Installing Net::Telnet 213 4.12.2 A Net::Telnet example 214 4.13 Where To From Here? 217 4.14 Print Resources 217 4.15 Web Resources 217 5 Management 221 5.1 Simple Management with ICMP 222 5.2 Doing the Ping Thing 222 5.2.1 Some ping examples 223 5.3 Doing the Net::Ping Thing 225 5.4 Tracing Routes 227 5.4.1 How traceroute works 228 5.5 Not So Simple Management with SNMP 229 5.5.1 A little SNMP history 229 5.6 The SNMP Management Framework 230 5.7 Managed Data 231 5.7.1 The TCP/IP MIB 231 5.8 The SNMP Protocol 235 5.8.1 SNMP’s operational model 235 5.8.2 A brief tour of SNMPv1, SNMPv2 and SNMPv3 235 5.8.3 SNMP communities 237 5.9 The Net::SNMP Module 237 5.9.1 The Net::SNMP methods 238 5.10 Working With Net::SNMP 240 5.10.1 Working with mnemonic object identifiers 242 5.10.2 The udpstats source code 243 5.10.3 The howlongup program 247 5.11 What’s Up? 249 5.11.1 Being more careful 254 5.12 Setting MIB-II Data 256 5.13 IP Router Mapping 258 5.14 Where To From Here? 266 5.15 Print Resources 266 5.16 Web Resources 267 6 Mobile Agents 269 6.1 What is a Mobile Agent? 269 6.1.1 Mobile agent = code + state 270 6.1.2 What is a mobile-agent environment? 270 6.2 Mobile-Agent Examples 270 6.2.1 Revisiting multiwho 270 6.2.2 Revisiting ipdetermine 271 6.3 Mobile-Agent Advantages/Disadvantages 272 6.4 Perl Agents 274 6.4.1 Preparing Perl for mobile agents 274 6.5 The Agent.pm Module 275 6.6 Ooooh, Objects! 276 6.7 The Default Mobile Agent 276 6.8 A Launching Mobile-Agent Environment 280 6.9 A One-Shot Location 282
  • 18. Contents xi 6.10 Relocating To Multiple Locations 284 6.10.1 Processing multiple mobile agents 285 6.10.2 Identifying multiple locations 285 6.10.3 A multi-location mobile agent 287 6.11 The Mobile-Agent multiwho 292 6.12 The Mobile-Agent ipdetermine 293 6.13 The Cloning Mobile-Agent ipdetermine 297 6.14 Other Perl Agent Examples 304 6.15 Where To From Here? 305 6.16 Print Resources 305 6.17 Web Resources 305 Appendix A. Essential Linux Commands 307 Appendix B. vi Quick Reference 311 Appendix C. Network Employed 315 Appendix D. Sample NetDebug Results 317 Appendix E. The OIDs.pm Module 363 Index 369
  • 20. Preface The study of Computer Networking, long considered an adjunct to traditional third-level computing programmes, has moved into the mainstream. The Insti- tute of Technology, Carlow, where I lecture, was the first third-level college in Ireland to develop an advanced four-year degree programme devoted entirely to the study of Computer Networking. Students learn computing from a networking perspective, and are trained in traditional programming technologies such as C, C++ and Java. In addition, the established degree programmes have been peri- odically reviewed to include new mainstream technologies, with recent emphasis on including the technologies associated with computer networks, concentrating, from a programming perspective, on network sockets. Using a traditional programming language to program network sockets (and networks in general) is a well-established practice. Unfortunately, some students have difficulty grasping the details of these languages, and, consequently, struggle with the complexities of programming network sockets. However, when a higher- level language like Perl is used, students are more comfortable with it and enjoy greater programming success. Of course, there is more to programming the network than programming net- work sockets. The modern network programmer needs to be able to analyse the network traffic programs generate, interact with standard network protocols, and manage complex networked systems. What is in this book This book supports the study of computer networking through the medium of Perl programming. Following an introduction to Perl (in Chapter 1, Meet Perl), the focus is on debug- ging. Programmers know how to debug programs. When it comes to the network, they need to know how to debug communications. In Chapter 2, Snooping, some simple Perl programs are built to capture and analyse the traffic network applica- tions generate. In the absence of any custom network applications, these simple programs are used to analyse the traffic generated by some standard network technologies.
  • 21. xiv Preface With the analysis tools in place, Chapter 3, Sockets, details the creation of a col- lection of custom network applications using the Socket application programmer interface. These are then developed to add increasing levels of sophistication. The experience of building networked applications is good preparation for interaction with the standard protocols of the Internet, the biggest computer net- work of all. In Chapter 4, Protocols, the standard and add-on facilities of Perl are used to interact with a selection of standard protocols and applications. It is important to build robust custom network applications. It is also important to be able to manage the networked environment within which these applications operate. The Internet provides a standard mechanism to do this, and Perl is used to program it in Chapter 5, Management. Programming the Network with Perl concludes with Chapter 6, Mobile Agents, which explores an area of computer networking that is generating considerable research. Many believe Mobile-Agent Technology to be one of the ‘next big things’ on the Internet. At the end of each chapter, a list of Print and Web Resources is provided to facil- itate further study. All chapters conclude with a set of programming exercises. Who should read this book? Programming the Network with Perl evolved from my involvement in teaching a 30 week computer networking module to a group of final-year undergradu- ate software engineers. The material presented here is derived from the practical material developed for the course. Since there is a high practical content related to the study of computer networking, Programming the Network with Perl is highly complementary to such a course. In addition, any course on programming Perl will benefit from the real-world examples illustrated. The professional Perl pro- grammer should also find the material interesting, as it is no longer enough to program the computer – the modern programmer needs to know how to program the network. Platform notes The Linux platform provides a host for our work. Not only is Linux a modern, feature-rich operating system, it is also available free of charge, and is, therefore, readily available. Linux provides excellent support to the Perl programmer. All the code in Programming the Network with Perl should run unaltered on any Linux platform, regardless of the underlying hardware technology. Users of UNIX or BSD derived systems should experience no real problems running the code. When working on Windows or Mac OS (prior to release X), getting the code in Chapter 2 to work will cause the most difficulty, although most of the code in the other chapters should run unaltered on these non-UNIX operating systems. For readers new to Linux, two appendixes provide quick references to the most frequently used Linux commands and to the vi text editor.
  • 22. Preface xv The network used during the development of Programming the Network with Perl is built from Ethernet hardware and TCP/IP software. The Ethernet network is connected to the global Internet via a cisco router and an ATM connection. The Network Employed appendix provides additional details on the network used (see the diagram on p. 316). Unless otherwise stated, use of at least release 5.6.0 of the Perl programming language is assumed. Accompanying website Details of the mailing-list, source code, errata and other material related to Pro- gramming the Network with Perl can be found on the book’s website, located at http://glasnost.itcarlow.ie/˜pnb/index.html. Your comments are welcome I welcome all comments (good and bad) about Programming the Network with Perl. Contact me via email at paul.barry@itcarlow.ie. Alternatively, write to me care of the publisher. Acknowledgments Thanks to Mark T. Sebastian for providing a detailed technical review of the manuscript, and to Greg McCarroll for his constructive criticism. My father, Jim Barry, thoroughly proof-read the entire manuscript and suggested many improve- ments to my writing style. A big thank-you to the team (Robert Hambrook, Jill Jeffries and Karen Mosman) at John Wiley & Sons, Ltd. Thanks to Michael Baker, John Hegarty, Austin Kinsella and Colm O’Connor at The Institute of Technology, Carlow. Thanks, too, to the students of CW082-4 for helping to debug many of the example programs. And hats off to Sam Clark (of T&T Productions Ltd) for turning my amateur L A TEX into that which you see before you now. I would like to acknowledge a small group of inventors for their inventions: Linus Torvalds for Linux, Bill Joy for vi, Leslie Lamport for L A TEX and, of course, Larry Wall for Perl. This book was inspired by the last invention, and produced with the first three. Programming the Network with Perl would never have been written without the continued support of my wife, Deirdre. While I worked on the manuscript, Deirdre looked after everything else. And with three little ones (all under 6 years of age), everything else was oftentimes quite a handful. Thanks, Deirdre.
  • 24. 1 Meet Perl This chapter introduces Perl to the non-Perl programmer. Competent Perl pro- grammers need only skim through this material. The main objective of this chapter is to provide sufficient Perl to allow read- ers to comfortably work through the rest of Programming the Network with Perl. Another is to show that Perl is a rather special programming technology: inter- esting, powerful, useful and fun. Newcomers to Perl are advised to work through a good introductory Perl text. See the Print Resources section at the end of this chapter for suggestions. For the purposes of this chapter, it is assumed that the reader is already a programmer. Veterans of the ‘C type’ languages may find much of Perl familiar. However, although Perl may look a lot like C, its behaviour is oftentimes a lit- tle strange, and can consequently be quite unlike C. Fans of other programming languages will, initially, just find Perl to be strange. Perl does not set out to be strange, but it is sometimes so unlike the mainstream programming languages that the differences are seen as strangeness in the eyes of ‘traditional’ program- ming folk. Which leads into the first bit of Perl strangeness: default behaviour. 1.1 Perl’s Default Behaviour Unlike other programming languages, Perl assumes a lot. It does a lot of things by default, and unless told otherwise, a Perl program will inherit this default behaviour. Think of this as Perl’s way of giving programmers something for noth- ing. This is unlike the vast majority of programming languages, which generally assume nothing, and where nothing is free.
  • 25. 2 Meet Perl 1.1.1 Our first Perl program A simple example1 will help to illustrate this default behaviour: #! /usr/bin/perl -w while (<>) { print; } The first line (all that #! stuff) looks a little strange, so let us conveniently ignore it, for now. The core of this program is the while loop, which is printing something with a print statement. Just what is getting printed is not clear, but as the print statement is in a loop, the assumption is that the printing is happening over and over again (as long as the condition of the while loop is true). But, what is getting printed? The answer lies in the bit of code that has not been explained yet. No, not the strange first line – that is still too strange to discuss – it is the other bit, the <> bit. If you are reading this and saying ‘that cannot do much’, then welcome to the wonderful world of Perl! The <> is a Perl operator which, unless Perl is told otherwise, hooks a program up to standard input and, when it appears in code, returns a line from standard input to the program. Magically, the line of input comes into the program at the top of the while loop, then makes its way (magically, again) to the print statement and gets printed! Now, if a selection of lines is fed to this program, they will all get printed one after the other (remember: the print statement is within a loop, so the code keeps executing while some condition is true). In this case, the program keeps going while there are input lines to process. To get lines into the program, pass them in from the keyboard (the hard way), or from a file (the easy way). Use the vi editor to create a file containing the Perl code as shown above. For want of a better name (and a distinct lack of imagination), let us call this program first. At the Linux command prompt, enter the following command to test the program’s functionality: perl first /etc/passwd The program should print each line from the /etc/passwd system file to the screen, one line at a time, until it runs out of lines. If something other than the content of the file appears, check to see if the Perl code has been typed in correctly. You can ask Perl to check code for syntax errors using the -c command-line switch. That is, typing perl -c first will check the first program for errors, but not run it. 1Borrowed rather shamelessly from Chapter 2 of Nigel Chapman’s book: Perl: The Programmer’s Companion. See the Print Resources section at the end of this chapter.
  • 26. Perl’s Default Behaviour 3 So, this program will, by default, use the filename from the command-line as standard input to the program. Perl finds the file, opens it, keeps reading from the file one line at a time until there are no more lines to read, then closes the file when the program ends. And all this behaviour happens by default. As if that were not enough, the program actually does more. If it is provided with more than one filename on the command-line, as follows: perl first /etc/passwd /etc/inittab .bash_profile it not only prints all the lines from /etc/passwd but, when it is done, moves onto /etc/inittab and prints all the lines in that file, before moving onto .bash_profile and printing any lines contained therein. Again, all this occurs by default, free of charge, no questions asked! A good question to ask at this point is: while the program is running, just where does Perl put the line that it reads in with <> and then prints out with print? We can answer this question after introducing another bit of Perl strangeness: the default variable. 1.1.2 Perl’s default variable Meet the default variable $_, the most used and abused variable in all of Perl. The general rule-of-thumb is this: if a piece of Perl code expects a variable to be used and one is not provided, 9 out of 10 pieces of code will use $_. This is exactly what happens with <> and print in the first program. The code could have been written as follows: #! /usr/bin/perl -w while ($_ = <>) { print $_; } To re-emphasize, this code is functionally identical to the code in the first pro- gram (albeit, somewhat more explicit). 1.1.3 The strange first line explained All that remains of the first program is an explanation of the strange #! line. This line is actually doing two things. As the # symbol in Perl indicates the start of a comment that extends to the end of the current line, the strange line is, first and foremost, a comment that is ignored by the Perl interpreter. Secondly, if the very first character of a file is # followed by a !, then the line takes on special meaning on Linux (and UNIX-like) systems. The #! combination tells the command processor to run the command identified by the rest of the line (in this
  • 27. 4 Meet Perl case, it is the /usr/bin/perl -w part), and then send the rest of the file to it as standard input. So, make the first program executable on Linux using the following command: chmod +x first and then invoke the program as follows: ./first /etc/passwd /etc/inittab .bash_profile Linux will find the Perl interpreter (rather conveniently called perl) located in the /usr/bin directory and run the contents of the first file through it. This is a cool feature of Linux (and UNIX), but of lesser importance if running on Mac OS (prior to X) or one of the Windows varieties. The -w part of the Perl command is a switch asking Perl to compile the code with extra warnings enabled. Until you know what you are doing, the advice is to always run Perl with the -w switch. Oh, by the way (and in case you hadn’t noticed), Perl statements end with the ; character, and blocks of code are enclosed in curly braces, { and }. Note, too, that Perl is case sensitive (so be careful). And Perl is an interpreter, which means that each time a program is run through Perl, the interpreter scans the code for errors, converts the code to Perl’s internal bytecode format, optimizes the bytecode, then runs it. If this all sounds slow, do not worry, in the big scheme of things, it really is not. Once a Perl program is actually running inside the interpreter, its performance compares favourably with the traditional compiled languages. Whew! We are finally done with the first program. Which just goes to show that it is sometimes much easier (and shorter) to write a few lines of Perl code than it is to explain them! 1.2 Using Variables in Perl So far, the only variable seen and used is $_, the default variable. Creating con- tainers for variables in Perl is easy. Give the container a name (which is made up of a combination of the letters A-Z, a-z, the digits 0-9 and the underscore charac- ter), then precede the name with one of Perl’s special variable naming characters, depending on what the variable will be used for: $ – a scalar variable (one of something); @ – an array variable (a collection of somethings, a list); % – a hash variable (a collection of name/value pairs); and – a referenced variable (a ‘pointer’ to something else, usually another variable).
  • 28. Using Variables in Perl 5 1.2.1 One of something: scalars When looking for a place to put one copy of something within a Perl program, use a scalar. Here are some examples: $greeting = "Welcome to Perl!"; $score = 20; $score = "Goal!"; $next = <>; $_the_answer = 42; $WhoWantsToBeA = 1_000_000; Some readers may be looking at the $greeting variable and saying ‘that’s not one of something, that’s three words’, but they would only be half right. Yes, it is three words, but they are contained within one single string, and Perl refers to this single string with a scalar variable container. Other readers may find it interesting (even strange) that the variable $score is being set to two different types of values – one a number (20) and the other a string (‘Goal!’). Assuming that these six lines were in fact a little Perl program, surely the Perl interpreter would complain that the second usage of $score causes an error, as $score was initially used within a numeric context? On the contrary, Perl does not care what value is assigned to a scalar2 , because Perl has no real notion of variable types, at least not like that which readers might be used to in C, C++, Pascal, or Java. So, it is OK (with Perl) to assign seemingly different typed values to the same scalar variable. Note that variable names can start with and include the underscore character, which can also be used to make literal numbers easier to read – simply place an underscore where it is usual to expect a comma. So: $WhoWantsToBeA = 1_000_000; is equivalent to: $WhoWantsToBeA = 1000000; whereas: $WhoWantsToBeA = 1,000,000; sets the variable $WhoWantsToBeA to 1, but readers will have to wait until lists are covered to find out why. In the code, the $next variable is assigned the result of Perl processing the <> operator. What happens is that a line of text from standard input is read into the program and assigned to the $next variable. Note that <> on a line by itself within a program does not take a line from standard input and put it into the $_ variable, as this behaviour only works within loops, as was the case with the 2Well, just so long as it is one of something.
  • 29. 6 Meet Perl first program. Be warned: if the <> operator appears on a line by itself within a Perl program, a line is read in from standard input, but, as Perl has nowhere to put the contents of the line, it is discarded, never to be seen again (unless read again from standard input). Hence, the use of the $next variable in the above example. 1.2.2 A collection of somethings: arrays and lists Here is an example that shows a relatively standard usage of arrays and lists in Perl: @networks = (’Ethernet’, ’Token-Ring’, ’Frame-Relay’, ’ATM’); On the left of the assignment operator (the = symbol), there is an array called @networks. Note the prefixed @ character, which indicates that this is an array variable. On the right, there are four network names in the form of a Perl list. The four names are surrounded by single quotes, enclosed in parentheses, and separated by commas. The elements of the list are all ‘one of something’ scalar values (in this case, strings). This single line of code takes the four network names and assigns them to the first four elements of the @networks array. In Perl, array indices start counting from zero, and the first element is actually referred to as element 0. So, @networks is a four-element array with elements numbered 0, 1, 2 and 3. The current size of an array can be determined in one of two ways. Add one to the value of the largest index (using $#), or assign the array to a scalar variable: print "The size of the array is: ", ( $#networks + 1 ), "n"; $size = @networks; print "The size of the array is: $sizen"; will print the following: The size of the array is: 4 The size of the array is: 4 Looking at the code, the $size scalar value is substituted into the part of the dou- ble quoted string that gets printed. This process is called variable interpolation, and it will be returned to later on in this chapter. The first print statement is actually printing a list, made up of a string, an expression, and another string3 . Arrays in Perl are automatically dynamic, so it is possible to add elements to the array without first having to reserve space for them. Here is how to add more network names into the array: @networks = ( @networks, ( ’FDDI’, ’Arcnet’ ) ); 3Did you notice this?
  • 30. Using Variables in Perl 7 The $#networks variable now has the value 5, which means there are six elements in the array. Accessing a single, specific array element is accomplished using the standard square bracket notation. The code which follows prints the word Token-Ring (followed by the newline character): print "$networks[1]n"; When accessing a single, specific element of an array, we are no longer referring to a collection of somethings, we are instead referring to the single, scalar element located within the array (i.e. one of something). Hence, the use of the $ prefix in the previous example as opposed to the @ prefix, which would refer to the entire array. Surprisingly (or strangely), Perl does not complain when code refers to a sin- gle array element with the @ prefix. The following code will also print the word Token-Ring (followed by the newline character): print "@networks[1]n"; Technically, this is a single element array slice, and should be avoided in situations like this. Strange? Most definitely. Something to worry about? Probably not. Just be sure to prefix single-element array accesses with $ and everything will be OK. When used in a scalar context, arrays and lists have a value. An array has a numeric value equal to the number of elements in the array, whereas a list has a value equal to the first element in the list. This helps explain why the following sets $WhoWantsToBeA to 1 and not 1,000,000 as might initially be expected: $WhoWantsToBeA = 1,000,000; Scalar context can be forced on an array by use of the inbuilt scalar subroutine. This code tells Perl to treat the array as a scalar, even though it really still is an array: print "The size of the array is: ", scalar @networks, "n"; An experienced Perl programmer may frown at the initial technique used when creating the first version of the @networks array, which is repeated here: @networks = (’Ethernet’, ’Token-Ring’, ’Frame-Relay’, ’ATM’); and could be rewritten as follows: @networks = qw(Ethernet Token-Ring Frame-Relay ATM); This has exactly the same meaning as the initial code, and many Perl programmers prefer it (mainly due to the fact that the latter requires less typing). The qw is called the quoting operator and is shorthand for ‘quote words’.
  • 31. 8 Meet Perl 1.2.3 Hashes The third Perl variable container is the hash, more formally known as the asso- ciative array. Hashes are somewhat like arrays, in that they hold a collection of scalar somethings. However, whereas arrays are indexed using numeric values, hashes are indexed using string values (which are also called ‘keys’ or ‘names’). Each string value index has associated with it a scalar value. These associations are often referred to as name/value pairs. Hashes in Perl are prefixed with a % character. Here is a hash which will hold data on the maximum frame size for a collection of popular networking technolo- gies: %net_mtus; To refer to the entire hash, use the % prefixed name. To refer to an individual ele- ment, prefix the hash name with the $ character (just as was done when referring to individual array elements). Here is how to add an element (which is referred to as a ‘hash entry’) into the newly created hash: $net_mtus{’Ethernet’} = 1500; The name (or key) is the word Ethernet and has the value 1500 associated with it. Lists can be used to initialize a hash: %net_mtus = ( ’Token-Ring’, 4464, ’PPP’, 1500, ’ATM’, 53 ); The list (which should have an even number of elements) is taken to contain a set of name/value pairs. Note that this line of code refers to the entire hash using the % prefix. This is shorthand for the following functionally identical code: $net_mtus{’Token-Ring’} = 4464; $net_mtus{’PPP’} = 1500; $net_mtus{’ATM’} = 53; Yet another version of this code takes advantage of the Perl feature which aliases the => symbol with the comma. Additional (entirely optional) white space adds to the readability of this code, and helps to highlight the name/value pairs: %net_mtus = ( ’Token-Ring’ => 4464, ’PPP’ => 1500, ’ATM’ => 53 ); It is often useful to think of => as meaning ‘has the value’ when working with hashes. Of note here is that, just like arrays, hashes grow dynamically and automatically in Perl. Also important is the fact that hash keys are (and must be) unique4 . 4The same restriction applies to array indices, although there tends to be much less fuss made of this fact.
  • 32. Using Variables in Perl 9 When a hash entry is created, a value part does not need to be initially specified. The special value undef can be used to set a hash entry (or any variable) to the undefined value: $net_mtus{’SMDS’} = undef; The above code is identical to: $net_mtus{SMDS} = undef; the only difference being that the single quotes are missing around the SMDS. In ‘Perl-speak’, this is referred to as a bareword. If a hash name contains no white- space, the single quotes are generally not required. A convenient way to clear an entire hash is to set it equal to an empty list: %net_mtus = (); Hashes (and arrays, for that matter) are very useful ‘right out-of-the-box’. For the vast majority of the programs in Programming the Network with Perl, these inbuilt variable containers are all that is needed. However, on occasion, more complicated data structures help to simplify a solution. The problem with arrays and hashes is that they can only store scalar values. This restriction, on first glance, seems limiting in that it appears no method exists to provide for, say, storing an array in a hash entry, or storing a hash in an array element. This restriction is overcome by the use of references. 1.2.4 References A reference is a Perl scalar variable container that refers to something else. The ‘something else’ can be one of a number of things, including another scalar, array, hash, subroutine, or Perl object. In this subsection, references to scalars, arrays and hashes are described. References to subroutines and objects will be discussed in later sections. If a scalar reference refers to an array, the scalar reference can then be, for example, added to an existing hash, creating a hash entry that refers to an array. The entry in the hash is still a scalar value (satisfying the restriction placed on hash values), but as a reference, it now refers to something more complicated than a scalar – in this case, an array. Creating a reference is very easy. Simply place a before the thing to be refer- enced. Here is code which creates a reference to an existing array, then adds the reference into an existing hash: %networks = (); @ethernets = qw( Ethernet-II IEEE802.3 IEEE802.3-SNAP ); $e_ref = @ethernets; $networks{’Ethernet Standards’} = $e_ref;
  • 33. 10 Meet Perl The ’Ethernet Standards’ hash entry now refers to the @ethernets array. It is important to realize that the @ethernets array and the $e_ref scalar both refer to the same data. If the array is changed, then what the scalar refers to also changes. Think of the scalar reference as an alias to the array’s memory location. To access the array (referred to in the hash), dereference the hash entry: print "The Ethernet standards are: "; print "@{$networks{’Ethernet Standards’}}n"; As it is known that the $networks{’Ethernet Standards’} entry is a reference to an array, prefix the use of the hash entry with the @ symbol. (The hash entry is also enclosed in an extra pair of curly braces, although this is not strictly required.) Read this code as: ‘access the array referred to by the hash entry’. In the earlier code, the use of the $e_ref scalar is redundant. It is equally valid to write the code this way: %networks = (); @ethernets = qw( Ethernet-II IEEE802.3 IEEE802.3-SNAP ); $networks{’Ethernet Standards’} = @ethernets; Even this can be shortened, if the sole purpose of having the @ethernets array is to create a reference to it within a hash entry. Here is another, equally valid, way to code this: %networks = (); $networks{’Ethernet Standards’} = [ ’Ethernet-II’, ’IEEE802.3’, ’IEEE802.3-SNAP’ ]; By enclosing the list of array elements in square brackets, this code creates an anonymous array (i.e. one that has no name). The array is then assigned to a hash entry, and Perl is smart enough to use a reference. Here is some code which shows the creation and use of references to scalars and hashes: $scalar = 42; $refs = $scalar; print ’Both $scalar and $refs have the value: ’, ${$refs}, ".n"; %hash = ( ’Name’ => "Paul Barry", ’Book’ => "Programming the Network with Perl", ’Year’ => 2002 ); $array_of_hashes[0] = %hash; print "There’s a great book called "; print "${$array_of_hashes[0]}{’Book’} byn"; print "${$array_of_hashes[0]}{’Name’}, published in "; print "${$array_of_hashes[0]}{’Year’}.n";
  • 34. Using Variables in Perl 11 Unfortunately, as shown in this piece of code, the syntax for accessing an indi- vidual hash entry within an array of hashes is complex. To yield the string ‘Paul Barry’ from the array of hashes, the code referred to it as: ${$array_of_hashes[0]}{’Name’} which reads (from the inside out): ‘take whatever is at element zero of the @array_of_hashes array, treat it as a hash, then access the value paired with the Name key’. Thankfully, Perl provides an alternative syntax, which can reduce this level of complexity. It is possible to yield ‘Paul Barry’ like this: $array_of_hashes[0]->{’Name’} or like this: $array_of_hashes[0]{’Name’} When the -> appears between a right and left bracket pair – either ]{, }[, }{, or ][ – its use is not required. It is also possible to create and use anonymous hashes by enclosing the hash entries in curly braces. Here is another (equally valid) way to populate the first element of the $array_of_hashes array: $array_of_hashes[0] = { ’Name’ => "Paul Barry", ’Book’ => "Programming the Network with Perl", ’Year’ => 2002 }; Or, this code would also do: %hash = ( ’Name’ => "Paul Barry", ’Book’ => "Programming the Network with Perl", ’Year’ => 2002 ); $array_of_hashes[0] = { %hash }; When working with the %networks hash of arrays (from earlier), either of the following work, yielding the string ‘IEEE802.3’: ${$networks{’Ethernet Standards’}}[1]; $networks{’Ethernet Standards’}->[1]; $networks{’Ethernet Standards’}[1]; Which technique to use is a programmer preference, but be aware that many Perl programmers freely mix their use of each, so it is important to be able to recognize all of them. To check if some variable is a reference, use the inbuilt ref subroutine, which returns the type of reference as a string.
  • 35. 12 Meet Perl 1.2.5 Built-in variables The Perl interpreter defines (and uses) a large collection of built-in variables. The default variable ($_) has already been described. A full list of built-ins can be viewed in the perlvar manual page. Type this command at the Linux command- line to page through the material: man perlvar Here is a list of frequently used built-in variables (examples of their use – with explanations – appear throughout Programming the Network with Perl). $! – contains the operating system error code after some operation has failed. $| – the auto-flush variable, which when set to 1 switches off buffering when Perl writes to an output filehandle (such as standard output). With auto-flushing off, the output buffer will typically not get flushed until a newline character is written. $1, $2, etc. – the pattern-match variables, created as the result of successful pat- tern matches and regular expressions. $a, $b – used by the inbuilt sort subroutine when doing comparisons. $@ – when eval is used, $@ is set upon the return from eval. @_ – the default array, used when processing parameters inside Perl subroutines. @ARGV – contains the list of command-line parameters sent to a program. @INC – lists the series of directories Perl searches when loading (and looking for) add-on modules. %ENV – a hash containing the current contents of the operating systems environ- ment. %SIG – a hash of operating system signals and signal handlers. 1.2.6 Scoping with local, my and our Variable containers in Perl need not be declared prior to their first use. Perl will automatically create them as needed. As a direct result of this behaviour, all vari- able containers in Perl are global in scope. It is possible to localize a global variable container to a block of code using the inbuilt local subroutine. When local is used in a block, at the end of the block the variable will revert to the value it had prior to entering the block within which it appears. Within the block, the variable can be used in any which way. If the block of code invokes a subroutine, the local value is visible (not the global) within the invoked subroutine. Due to its strange behaviour, use of local tends to be frowned upon nowadays. Consequently, none of the code in Programming the Network with Perl uses local.
  • 36. Controlling Flow 13 The inbuilt my subroutine can be used to give a variable container lexical scope. The variable is not globally visible, nor is it visible by any invoked subroutine. It is only visible within the block that declares it. When the use strict compiler directive is used at the top of a Perl program, global variables are forbidden, and my must be used. That is, of course, assuming the variable containers have not been declared with our. The inbuilt our subroutine is new as of release 5.6.0 of Perl. When our is used, the variable container can be used as if it is global, even though it really is not. This allows a program to use the use strict compiler directive, and still use global variable containers when it is convenient (or necessary) to do so. 1.3 Controlling Flow Perl has the usual collection of flow control statements: if, while and for. Perl also has some of its own: unless, until and foreach. In addition, two built- in subroutines (do and eval) can impact on a program’s flow of control. In this section, we will look at each of these constructs in turn. 1.3.1 if To decide on one or more courses of action, use the if statement. Assuming the $net scalar is set to an appropriate value, a simple if statement might be: if ( $net eq ’Token-Ring’ ) { print "The network is of the token passing variety.n"; } This code prints the message if the condition-part (i.e. the first line) of the if statement is true. Veterans of the C-type programming languages need to note that the use of curly braces is required by Perl. Two-way decisions are accommodated by the use of an else statement: if ( $net eq ’Token-Ring’ ) { print "The network is of the token passing variety.n"; } else { print "The network is NOT a token passer.n"; } Multi-way decisions are also possible (note the strange spelling of elsif):
  • 37. 14 Meet Perl if ( $net eq ’Token-Ring’ ) { print "Your network is of the token-passing variety.n"; } elsif ( $net eq ’Ethernet’ ) { print "Your network is of the CSMA/CD variety.n"; } elsif ( $net eq ’Frame-Relay’ ) { print "Your network is of the ISDN variety.n"; } else # Assuming a value of ’ATM’ ... { print "Your network is of the cell-switching variety.n"; } This is the only way to perform a multi-way decision in Perl. C and Java program- mers may miss the convenience of the switch statement, just as Pascal program- mers may miss their case statement. To such programmers, Perl offers nothing more than a shrug of apology (and a nod in the direction of code similar to that shown above). 1.3.2 The ternary conditional operator Perl supports the ternary conditional operator. The following if statement sets the value of $do depending on the current value of $today: if ( ($today eq ’Sat’) or ($today eq ’Sun’) ) { $do = "Play"; } else { $do = "Work"; } and is functionally identical to this (somewhat more compact) code: $do = ( ($today eq ’Sat’) or ($today eq ’Sun’) ) ? "Play" : "Work"; The condition-part of the if statement comes before the ? symbol. If the condition-part is true, the value Play results, otherwise the value Work results (with the : symbol separating the two possible results). The variable $do is, there- fore, assigned an appropriate value.
  • 38. Controlling Flow 15 1.3.3 while The while statement was part of the first program written at the start of this chapter. Like the if, curly braces are required with while statements. Code inside the loop (i.e. within the curly braces) keeps executing while the condition-part of the while statement is true. A loop can optionally include a continue block which will execute at the end of each loop (or iteration). Three statements provide programmers with the ability to fine tune the behaviour of loops: next – jump immediately to the bottom of the loop and execute the continue block (if one exists), then start a new iteration if the condition-part evaluates to true; last – exit the loop, bypassing any continue block, and resume execution at the first statement immediately following the loop; redo – abandon the current iteration of the loop, jump to the first statement of the loop, and re-execute the loop statements. Example uses (with explanations where required) of these statements appear throughout Programming the Network with Perl. The while statement is often used to iterate through a hash, as follows: while ( ($name, $value) = each %net_mtus ) { print "$name has the value: $valuen"; } The inbuilt each subroutine returns a name/value pair from the specified hash, and with each iteration, the next name/value pair is returned until no more pairs are left. Of note is that the name/value pairs come out of the hash in no particular order (and most definitely not in the order that they were inserted). 1.3.4 for The for statement iterates a fixed number of times over code, and is typically used to process arrays. Here is how to print each element of the @networks array on its own line: for ($i = 0; $i <= $#networks; $i++) { print "$networks[$i]n"; } This code initializes $i to zero before the loop starts to iterate, then checks to see if the value of $i is less than or equal to the largest index of the array ($#networks). If it is, the loop iterates, then the value of $i is incremented after
  • 39. 16 Meet Perl the iteration completes, and prior to the test against $#networks is performed again. The loop iterates until the entire array has been printed. 1.3.5 unless In Perl, the unless statement is the opposite of if. This code prints the line for values of $net other than Token-Ring: unless ( $net eq ’Token-Ring’ ) { print "The network is NOT of the token passing variety.n"; } The unless statement can have an else part, but no elsifs. 1.3.6 until The while statement also has an opposite, the until statement. Rather than iterating while a condition is true, this statement iterates until some condition is true. 1.3.7 foreach The for statement described earlier is used so often to process arrays that a special shorthand version exists, the foreach statement. This code is identical to the example used with for above: foreach $i (@networks) { print "$in"; } But be careful: while inside the loop, the $i variable is an alias to the actual element within the @networks array. If $i is changed, so is the corresponding array element. The foreach statement can also be used to iterate over a hash: foreach $name ( keys %net_mtus ) { print "$name has the value: $net_mtus{$name}n"; } Another inbuilt subroutine, keys, returns a list of all the name-parts of the named hash. This list (array) is then used normally by the foreach. The keys subroutine can also be used, in conjunction with scalar to calculate the number of elements in any hash:
  • 40. Controlling Flow 17 $size = scalar keys %net_mtus; print "The size of the hash is: $sizen"; A common extension to the above hash traversal code is to call the sort or reverse inbuilt subroutine to force an ordering on the hash name-parts: foreach $name ( sort ( keys %net_mtus ) ) { print "$name has the value: $net_mtus{$name}n"; } 1.3.8 do The do subroutine takes a block of code as its sole parameter, and executes the block of code, returning the value of the last line of the code as the result of the do. The following example sets the value of $res to 15, then prints the value to the screen, and illustrates the basic mechanism: $res = do { $a = 5; $b = 3; $a * $b; }; print $res; A second form of do takes the name of a file as its sole parameter and executes the contents of the file as a Perl program. Assuming a file called es1 exists in the current working directory, this code opens the file from within the current program and runs any Perl code contained therein: do ’es1’; 1.3.9 eval The eval subroutine takes a string as its sole parameter and executes the string as a Perl program (or fragment thereof). This code does the same thing as the do example: $some_code = ’$a = 5; $b = 3; $res = $a * $b; print $res;’; eval { $some_code }; What makes this eval code different5 from the equivalent do code is that a certain amount of protection is provided by eval. Specifically, if the code within the eval 5Some would say ‘better’.
  • 41. 18 Meet Perl block causes a fatal error (which would normally cause the Perl interpreter to exit immediately from a program), eval catches the fatal error and provides a way to recover from the error. The built-in variable $@ will be set by eval on exit from the code block. If the value of $@ is set to the empty string, no fatal error occurred. However, if the value of $@ contains a non-empty string, a fatal error occurred and a description of the error is in $@. This, therefore, provides a simple, yet highly useful, exception-handling mechanism. In the code which follows, a call to the inbuilt die subroutine causes the gen- eration of a fatal error (and message). When called outside an eval block, the program would end immediately. When called inside an eval block, the evalu- ated code ends and the $@ variable is set to the message from die. Here is an eval example: eval { print "This is Apollo 13. Mission Log.n"; print "We are half-way to the Moon.n"; die "Houston, we have a problem!n"; }; if ($@) { print "Message from Apollo 13 - $@"; print "Let’s bring them home safely ... "; } else { print "Maybe 13 is not that unlucky after-all ... "; } Due to the fact that the call to die is within the eval block, the program can recover gracefully from what would otherwise be a fatal error (and go on to save the astronauts). The else part of the if statement will never execute in this code, but is included here for illustration only. 1.3.10 Statement modifiers In addition to the control flow mechanisms which enclose blocks of code, Perl also provides support for statement modifiers. With these, individual statements can be qualified. A series of examples will help to illustrate. This code prints the words ‘Hello World’ if the value of $should_we has some value (i.e. if it is defined): print "Hello World" if defined( $should_we ); This code prints the words ‘Hello World’ unless the value of $today is Saturday: print "Hello World" unless $today eq ’Saturday’;
  • 42. Boolean in Perl 19 This single line of code is another way of writing the first program from the start of the chapter. The code takes lines of input from standard input (one at a time) and prints them. It keeps going until there is no more input lines to process: print while (<>); It is possible to use until anywhere that while is used, and this is also true of statement modifiers. When combined with do, statement modifiers provide for loops that will iterate at least once, as the condition-part of the loop comes at the end of the block. Here is the general form of the do. . .while construct: do { # Do something ... } while # some condition is true; and here’s the general form of a do. . .until: do { # Do something ... } until # some condition is true; 1.4 Boolean in Perl Strangely, Perl has no inbuilt Boolean type6 . Instead, any Perl expression can be used as a condition, and can be evaluated to be either true or false. A number of rules help determine whether something is true or false as follows. Strings – a string is true, unless it contains "0" or the empty string. (Strangely, "00" and "0.00" are true.) Numbers – a number is true, unless it evaluates to zero. (Strangely, this means −42 is true.) References – all references are true. (This is initially quite strange until one con- siders what a reference contains.) Undefs – anything with the undefined value is false. (This is not strange – how can anything that is undefined possibly be true?) Lists – empty lists are false, lists with any number of elements are true. (Like undef, this is not at all strange.) 6Are you not getting used to all this Perl strangeness yet? After a while, it all becomes quite normal. Strange, but true.
  • 43. 20 Meet Perl 1.5 Perl Operators In a number of the code examples seen so far, various code snippets have relied on condition tests that have used comparison operators. They have been rather sneakily used, without providing any detailed description. Nobody likes a sneak, so here is the entire list of Perl operators (with brief explanations) in precedence order, starting with those with the highest precedence. -> – the infix dereference arrow operator, used when working with references (and objects). ++ and -- – the increment and decrement operators. ** – the exponential operator. !, ˜, , + and - – the logical negation (!), bit-wise negation (˜), reference (), numeric affirmation (+) and arithmetic negation (-) operators. =˜ and !˜ – the binding operators (used when working with regular expressions and pattern matches). *, /, % and x – the multiply, divide, modulus (%) and repetition (x) operators. +, - and . – the addition, subtraction and concatenation (.) operators. << and >> – the left and right bit shifting operators. <, >, <=, >=, lt, gt, le and ge – the relational operators. There are two of each, one for working with numbers and the other for working with strings. Be careful to use <, >, <= and >= when comparing numbers, and use lt, gt, le and ge when comparing strings. ==, !=, <=>, eq, ne and cmp – the equality operators. As with the relational oper- ators, different versions exist for use with numbers and for strings. The <=> and cmp operators are used for comparison, and are typically used in con- junction with the inbuilt sort subroutine. & – the bit-wise AND operator. | and ˆ – the bit-wise OR and eXclusive OR operators. && – the logical AND operator. || – the logical OR operator. .. and ... – the range operators. ?: – the ternary conditional operator. =, **=, +=, *=, &= and so on – the assignment operators. , and => – the comma operator (typically used to separate list items). not – a lower precedence alternative to !. and – a lower precedence alternative to &&.
  • 44. Subroutines 21 or and xor – lower precedence alternatives to || and a logical eXclusive OR oper- ator. 1.6 Subroutines Perl supports the creation of named, user-defined blocks of code, which go by the generic name of ‘subroutine’7 . Creating subroutines could not be easier: give the subroutine a name, pass the name to the inbuilt sub subroutine together with the block of code. Here is a simple example: sub simple { print "Hello from the simple subroutine!n"; } The subroutine can now be invoked (from within the program that defined it) in one of four ways: simple; simple(); &simple; &simple(); It rarely matters which of these techniques is used, as they all do the same thing, i.e. invoke simple. When Perl gets picky about a particular style of invocation, the interpreter will tell you. 1.6.1 Processing parameters Every user-defined Perl subroutine can take any number of parameters. If simple was invoked as: simple( "Hey! Print this!n" ); it would simply ignore the parameter, and Perl would not complain. Any parame- ters that are sent to a subroutine become available within the default array, which is called @_. Here is another version of simple that can process parameters: sub simple { $print_what = $_[0]; print $print_what; } where $_[0] refers to the first element of the @_ array. To print the entire array contents, use this code: 7Also known as ‘function’, ‘procedure’, ‘routine’ and/or ‘method’, depending on your program- ming background.
  • 45. 22 Meet Perl sub simple { print "@_"; } If more than one parameter is passed, each becomes available within the subrou- tine as a separately accessible array element. Let us assume that another version of simple supports calls like this: simple( "On line one", "On line two" ); To access each ‘line’ within simple, the subroutine could be rewritten to access each element of the default array: sub simple { print $_[0], "n"; print $_[1], "n"; } This technique is rarely seen, as most seasoned Perl programmers prefer to take advantage of the inbuilt shift subroutine, which removes and returns the first element from a named array, or the first element from the default array if no array is specified. Once again, a rewritten simple illustrates this technique: sub simple { print shift, "n"; print shift, "n"; } It is important to realize that when parameters are passed to any user-defined subroutine, they are ‘flattened’ into a list. So, if a subroutine is written to expect as parameters a hash, followed by an array, and then a scalar, the three parameters will enter the subroutine as one long, flattened list (which is rarely what was wanted). Pass the hash, array, and scalar as references to ensure they arrive in the subroutine in the correct format. In this case, the @_ default array will contain three elements: a hash reference, an array reference, and a scalar reference. Note, too, that when accessed inside the subroutine, the references refer to the original variable containers, so if they are changed within the subroutine, they will be changed elsewhere. By default, all parameters are passed by value. 1.6.2 Returning results A subroutine can return a value, and unless explicitly stated, this will be the value of the last statement in the subroutine. The simple subroutine would therefore return a true value (assuming the call to print was successful). To control what value is returned, use the inbuilt return subroutine:
  • 46. Subroutines 23 sub simple { my $count = 0; print shift, "n"; $count++; print shift, "n"; $count++; return( $count ); } This code will (always) return the value 2. 1.6.3 I want an array Perl subroutines can be written to return either a scalar or a list. Consider the inbuilt keys subroutine introduced during the discussion of hashes. When called in what is known as list context, keys returns a list of hash name-values. When called in scalar context, keys returns the number of elements in the hash. By employing the services of the inbuilt wantarray subroutine, it is possible to write a user-defined subroutine that works in a similar fashion: sub return_hash_keys { %a_hash = @_; return ( wantarray ? keys %a_hash : scalar keys %a_hash ); } %net_mtus = ( ’Token-Ring’ => 4464, ’PPP’ => 1500, ’ATM’ => 53 ); @keys = return_hash_keys( %net_mtus ); print "Hash keys: @keysn"; $size = return_hash_keys( %net_mtus ); print "Hash size: $sizen"; The wantarray subroutine knows whether the user-defined subroutine has been called in list or scalar context. If called in list context, wantarray evaluates to true. 1.6.4 In-built subroutines Perl has a large collection of inbuilt subroutines. The entire collection is docu- mented in the perlfunc online documentation. Use this command to view the manpage: man perlfunc
  • 47. 24 Meet Perl Alternatively, use the perldoc program (which comes with Perl) to search the perlfunc manpage for documentation on a specific subroutine. For instance, to view the documentation for the inbuilt print subroutine, use this command: perldoc -f print The inbuilt subroutines take a varying number of parameters. Check the documen- tation for specifics. Be aware that some inbuilt subroutines can do different things based on how they are invoked and used. The code in this chapter has already used some of the more popular inbuilt subroutines. Here is an abbreviated list8 : alarm – signal an alarm to occur a number of seconds in the future; chomp – deletes the trailing newline character from a scalar; chop – deletes the last character from a scalar; close – close a previously opened filehandle; defined – returns true if a variable has a value associated with it; delete – delete elements/entries from an array/hash; die – exit the current program after displaying a user-specified message; do – execute a block of statements as one, or read in a collection of statements from another file and execute them; each – used to iterate over a hash; eof – test for the end-of-file condition; eval – evaluate a block of code, and provide exception handling; exists – returns true if a specific array element or hash entry exists; exit – exit the current program; fork – create a child process which is a clone of the current process; gmtime – return the date and time relative to GMT; goto – jump to a labelled location within a program9 ; join – join a list of strings together; keys – returns a list of keys for a specified hash; last – exit from the current loop; length – return the length of a scalar variable; local – localize a variable; localtime – return the date and time relative to the local time zone; my – mark a variable as being lexically scoped; 8Subroutines of specific interest to network programmers are not presented here, as they are the subject of Chapter 3. 9But real programmers never use goto, do they?
  • 48. Subroutines 25 next – start the next iteration of the current loop; open – open a file, and associate a filehandle with it; our – declare a global variable; pack – convert a collection of variables into a string of bytes; package – declare a new namespace; pop – treat an array like a stack, and pop the last element off the end of the array; print – print something (to a named output handle); printf – print to a particular format; push – treat an array like a stack, then push an element onto the end of the array; read – read a specified number of bytes from a filehandle; redo – restart the current loop iteration; ref – check to see whether a scalar is a reference, and if it is, return the type of reference as a string; return – return a value from a subroutine; scalar – force a list to be treated as if it were a scalar; shift – treat an array like a stack, and pop the first element off the start of the array; sleep – pause execution for a specified number of seconds; sort – sort a list using string comparison order (by default), or by using some user-specified ordering; splice – remove specified elements from an array; split – split a delimited string into a list of individual elements; sprintf – like printf, except the result is assigned to a scalar; sub – declare a subroutine; substr – extract a substring from a string; system – call an operating system command, and return its exit status to the calling program; time – returns the number of non-leap seconds since the operating system’s ‘epoch’10 ; undef – take a previously defined variable, and undefine it; unpack – the reverse of pack: extract a list of values from a string of bytes; unshift – treat an array like a stack, and push an element onto the start of the array; wait – wait for a previously created child process to terminate; 10What the operating system thinks is the start of time. It varies from system to system.
  • 49. 26 Meet Perl wantarray – return true if a subroutine was called within a list context, false otherwise; warn – sends output to standard error; write – write a specified number of bytes to a filehandle. Example uses of these inbuilt subroutines appear throughput Programming the Network with Perl. If their meaning is not clear from the context in which they are used, further description is provided. 1.6.5 References to subroutines Perl allows references to subroutines. Here is a preview of a code snippet from the end of Chapter 2 which assigns a subroutine reference to a scalar called $packet_handler based on the value of another scalar called $opt_u: if ($opt_u) { $packet_handler = &udp_both_packet; } else { $packet_handler = &tcp_both_packet; } Note the use of the character which turns the call to the subroutine into a refer- ence to the subroutine. Later in the code, the previously selected subroutine can be invoked as follows: &$packet_handler; 1.7 Perl I/O Performing input and output (I/O) in Perl is as simple as it gets. Disk files have associated filehandles, and each time some input and output is performed, the code need only reference the correct filehandle to work. Filehandles can be opened to read from, write to, or read/write to/from. Four filehandles are automatically opened for every Perl program: STDIN, STD- OUT, STDERR, and DATA. These correspond to standard input (usually the key- board), standard output (usually the screen), standard error (usually the screen, but sometimes a system log file), and the thoroughly strange ‘standard data’. The DATA filehandle is associated with anything that comes after the __END__ symbol at the end of a source code file, and is generally useful when testing code prior to deployment.
  • 50. Perl I/O 27 To read from a filehandle, enclose the filehandle in the <> angle brackets. This code reads a line from standard input: $line = <STDIN>; which is longhand for: $line = <>; as Perl will assume standard input by default. Writing to output filehandles usually involves the use of the inbuilt print subroutine. Here is how to write to standard output: print STDOUT "Writing to standard output, usually the screen.n"; which is longhand for: print "Writing to standard output, usually the screen.n"; as Perl will assume standard output by default. To write to standard error, use code similar to this: print STDERR "Writing to standard error.n"; or use the inbuilt warn subroutine which will always write to STDERR: warn "Writing to standard error.n"; To create filehandles, give them a name and associate them with a file. By conven- tion, filehandle names are specified in uppercase, although Perl does not enforce this as a rule. To open a file for reading, use code similar to the following: open MYINFILE, "readme.txt" or die "Could not open: $!"; This code will open readme.txt and associate it with the MYINFILE filehandle, or if something goes wrong, exit with an appropriate error message. Once a filehandle is opened, read from it using the <> operator: $a_line = <MYINFILE>; @entire_file = <MYINFILE>; Here the <> operator is used in both scalar and list context. Be careful when using <> in list context, as reading a large file in one go can result in memory problems. To close a filehandle, call close on the filehandle name: close MYINFILE; which Perl will do anyway when your program ends.
  • 51. Another Random Scribd Document with Unrelated Content
  • 52. In December Suchet completed the formal conquest of Aragon, by moving up the whole of Laval’s division into the high-lying district of Teruel, in the extreme south-east of the province, the only part of it that had never yet seen the French eagles. The Junta of Aragon fled from thence over the border of the kingdom of Valencia, but Villacampa and his bands remained in the mountains unsubdued, and while they continued to exist the conquest of the upland was incomplete. The moment that its towns ceased to be held by large garrisons, it was clear that the insurgents would descend to reoccupy them. Nevertheless Suchet had done much in this year: besides the crushing of Blake he had accomplished the complete subjection of the plains of Central Aragon, and had obtained a grip upon its two mountain regions. He had fortified Monzon, Fraga, Alcañiz, and Caspe as outposts against the Catalans, and, having received large drafts from France in the autumn, was on the last day of the year at the head of a fine corps of 26,000 men, from which he might hope to produce in the next spring a field army sufficient for offensive operations against Catalonia or Valencia, after providing garrisons for his various posts of strength[16] . The weak point of his position was that the guerrilleros had learned caution, refused for the future to fight save under the most favourable conditions, and devoted themselves to the safe and vexatious policy of intercepting communications and cutting up small parties and stragglers. They were much harder to deal with, when once they had learnt that not even in fastnesses like El Tremendal or San Juan de la Peña was it wise to offer the French battle. Unless Suchet left a garrison in every town, nay, in every considerable village, of the sierras, the insurgents dominated the whole region. If he did take such measures for holding down the upland, he was forced to immobilize a very large proportion of his army. We shall note that in 1810 he was only able to draw out 12,000 of his 26,000 men for the invasion of Western Catalonia. While the commander of the 3rd Corps was making steady progress with the conquest of Aragon, the fortunes of his colleague of the 7th Corps had been far more chequered. Indeed for the
  • 53. greater part of 1809 St. Cyr was brought to a complete standstill by the unexpected obstinacy of the gallant garrison of Gerona, who for no less than eight months kept the main body of the army of Catalonia detained in front of their walls. When last we dealt with the operations in this region we left St. Cyr victorious at the well-contested battle of Valls, after which he advanced into the plain of Tarragona, made some demonstrations against that fortress, but returned after a few weeks to Barcelona (March 18) without having made any serious attempt to turn his victory to practical account. This retreat after a brilliant success may be compared to Victor’s similar evacuation of Southern Estremadura after Medellin, and was brought about, in the main, by the same cause, want of supplies. For when he had consumed the resources of the newly-subdued district between Valls and Tarragona, St. Cyr had no means of providing his army with further subsistence. Barcelona, his base, could not feed him, for the city was itself on the edge of famine: it was still beset to north and west by the local miqueletes, who had returned to their old haunts when the main French army had gone off southward on the campaign of Valls. It was stringently blockaded on the sea side by the British Mediterranean fleet, and it could not draw food from France by land, because the high-road to Perpignan passed through the fortress of Gerona, which was still in Spanish hands. St. Cyr himself, it will be remembered, had only reached Barcelona by turning off on to side tracks through the mountain, and winning his way down to the shore by the hard-fought battle of Cardadeu. Till Gerona should fall, and the garrison of Barcelona be placed in direct communication with France, there was little use in making ambitious offensive movements against Tarragona or any other point in Southern or Central Catalonia. It was absolutely necessary to reduce Gerona, and so to bring the division left behind under Reille, in the Ampurdam and on the frontier of Roussillon, into free communication with the remainder of the 7th Corps. From the moment when St. Cyr passed the mountains during the winter Reille had been fighting out a petty campaign against the northern Catalans, which had no connexion
  • 54. whatever with his superior’s operations at Molins de Rey and Valls, and had little definite result of any kind. No one saw more clearly than Napoleon the need for the reduction of Gerona: as early as January he had issued orders both to St. Cyr and to Reille to prepare for the enterprise. But St. Cyr was now out of touch, and Reille was far too weak in the early spring to dream of any such an adventure: he had been left no more than seven depleted battalions to maintain his hold on Northern Catalonia, when St. Cyr took the rest of the army across the hills to Barcelona. The Emperor was not slow to realize that the 7th Corps must be reinforced on a large scale. He did so by sending thither in the spring of 1809 a brigade of Berg troops (four battalions), the regiment of Würzburg (two battalions), and a division (seven battalions) of Westphalians: it will be noted that now, as always, he was most chary of drafting native French troops to Catalonia, and always fed the war in that direction with auxiliaries in whose fate he was little interested: the campaign in eastern Spain was, after all, but a side issue in the main struggle[17] . When these reinforcements had arrived Reille began to collect material at Bascara on the Fluvia, to which siege-guns laboriously dragged across the Pyrenees were added: several companies of heavy artillery and sappers were brought up from France. St. Cyr meanwhile, four weeks after his retreat from the plain of Tarragona, moved on to Vich upon April 18, with the divisions of Souham, Pino, Lecchi, and Chabot, leaving Duhesme with his original French division, which had held Barcelona since the outbreak of the war, in charge of his base of operations. His departure was partly designed to spare the stores of Barcelona, where the pinch of famine was beginning to be felt; for he intended to subsist his army on the upland plain of Vich, a rich corn-bearing district hitherto untouched by the war. But a few days after he had marched forth Barcelona was freed from privation, by the lucky arrival of a squadron of victuallers from Toulon, convoyed by Admiral Cosmao, which had put to sea in a storm and eluded the British blockading squadron (April 27). The position of Vich, however, had been chosen
  • 55. by St. Cyr not only for reasons of supply, but because the place was happily situated for covering the projected siege of Gerona against any interruption by Blake. If the Spanish commander-in-chief brought up the wrecks of the old Catalan army from Tarragona, with his Valencian levies added, he would almost certainly take the inland road by Manresa and Vich, since the coast-road was practically barred to him by the French occupation of Barcelona. As a matter of fact the commencement of the leaguer of Gerona was not vexed by any such interruption, for Blake had his eyes fixed on Saragossa in May and June, and was so far from dreaming of an assault on St. Cyr, that he drew off part of the Catalan army for his unhappy invasion of Aragon, which finished with the disaster of Belchite. During the early months of this long siege the only external helpers of the garrison of Gerona were the small force of regulars under the Swiss Wimpfen, and the miqueletes of Claros and Rovira from the Ampurdam, Reille’s opponents during the spring. At Tarragona the Marquis of Coupigny, the senior officer now in Catalonia, had no more than 6,000 men left of Reding’s old army, and was helpless to interfere with St. Cyr who had some 20,000 men concentrated at Vich. The preparations for the siege therefore went on in the end of April and the beginning of May without any hindrance, save from the normal bickerings of the French outlying detachments with the local somatenes, which never ceased. Around Vich matters were particularly lively, for the whole population of the town and the surrounding plains had gone up into the hills, where they wandered miserably for three months, much hunted by French foraging parties, which they occasionally succeeded in destroying. St. Cyr opened up his communications with Reille by sending to him Lecchi’s Italian division, which cut its way amid constant skirmishes along the banks of the Ter to Gerona, and met the troops from the Ampurdam under its walls. Reille had moved forth from Bascara on May 4, and on the eighth expelled the Spanish outposts from all the villages round the fortress, not without some lively skirmishing. He had brought up some 10,000 infantry—including his own old division and all the
  • 56. newly arrived Germans—with some 1,300 artillerymen and engineers. Almost at the same moment arrived dispatches from Paris, announcing that the Emperor, just before departing for the Austrian war, had superseded both St. Cyr and Reille, being discontented with their handling of affairs in Catalonia. It is unfortunate that no statement in detail of his reasons appears in the Correspondance[18] , but it would seem that he thought that the victories of Molins de Rey and Valls should have had greater results, disapproved of St. Cyr’s retreat from in front of Tarragona, and thought that Reille had shown great weakness in dealing with the insurgents of the Ampurdam. He ignored the special difficulties of the war in Catalonia, thinking that the 30,000 men of the 7th Corps ought to have sufficed for its complete conquest. Indeed he showed his conception of the general state of affairs by recommending St. Cyr in March to undertake simultaneously the sieges of Gerona, Tarragona, and Tortosa[19] . The leaguer of one, and that the smallest, of these places was destined to occupy the whole army of Catalonia, when largely reinforced, for eight months. If it had been cut up according to the imperial mandate, it is probable that at least one of its sections would have been destroyed. St. Cyr wrote in his memoirs that his master was jealous of him, and wished to see him fail, even at the cost of wrecking the 7th Corps. This is of course absurd; but there can be no doubt that the Emperor disliked his lieutenant, all the more because of the long string of complaints, and of demands for more men, money, and stores, which he was now receiving week by week from Catalonia. He loved generals who achieved the impossible, and hated grumblers and frondeurs, a class to which St. Cyr, despite all his talents, undoubtedly belonged. It is possible that Napoleon’s determination to replace him may have been fostered by intrigues on the part of the officer to whom the 7th Corps was now turned over. Marshal Augereau had served with great credit in the old republican campaign in Catalonia during 1793 and 1794, imagined himself to have a profound knowledge of the country, and was anxious to try his hand in it. It was many years since he had been trusted with an independent command; both in the wars of 1806-7 and in that of 1809 he had been lost in the ranks
  • 57. of the Grand Army. His nomination to supersede St. Cyr was made early in May, but on his way to the seat of war he was seized with a fit of the gout, and was detained in bed at Perpignan for many weeks. Thus his predecessor, though apprised of his disgrace, was obliged to continue in command, and to commence the operations of which the Marshal, as he well knew, would take all the credit. At the same moment Reille was displaced by Verdier, the general who had conducted the first unlucky siege of Saragossa—an experience which seems to have made him very cautious when dealing with Spaniards behind walls. Lecchi’s division forced its way back to St. Cyr on May 18, bringing him the intelligence of his supersession, but at the same time apprising him that Augereau would not arrive as yet, and that the duty of commencing the siege of Gerona would still fall to his lot. At the same time Verdier sent letters urging that his 10,000 infantry formed too small a force to surround such a large fortress, and that he must ask for reinforcements from the covering army. If they were denied him, he should refuse to begin the siege, throwing the responsibility for this disobedience of the Emperor’s commands on his superior: he had reported the situation to Paris. St. Cyr was incensed at the tone of this dispatch[20] , above all at the fact that Verdier was appealing straight to the Emperor, instead of corresponding through his hierarchical superior, according to the rules of military etiquette. But he saw that Verdier had a good case, and he had just learnt that Blake had turned off against Aragon, so that no trouble from that quarter need be feared. Accordingly he, very grudgingly, sent back Lecchi’s division to Gerona. It was the worst that he possessed, being composed of no more than four Neapolitan and three Italian battalions, with a strength of little over 3,000 bayonets[21] . He added to it a regiment of Italian light horse, several of his own batteries, and nearly all the engineers and sappers of his corps, so that the total reinforcement sent to Verdier consisted of more than 4,000 men. Having received these succours, which brought up his total force to 14,000 infantry and cavalry, and 2,200 artillerymen, sappers and
  • 58. engineers, Verdier commenced on May 24 his operations against Gerona: on that day Lecchi’s division took its post in the plain of Salt, on the west of the town, while the French and Westphalian divisions were already close to the place on its eastern and northern sides. The head quarters and the French brigades of Joba and Guillot lay by Sarria and the bridge of Pont-Mayor, where the magazines were established, while the Germans had been sent up on to the heights east of the fortress and held the plateaux of Campdura, San Medir, and Domeny. The rocky southern side of Gerona, in the direction of the gorge of the Oña, was not yet properly invested. Something has already been said, in an earlier volume of this work, concerning the situation of Gerona, when its two earlier sieges by Duhesme were narrated[22] . It must suffice to repeat here that the town is built on the steep down-slope of two lofty heights, with the river Oña at its foot: the stream is crossed by two bridges, but is fordable everywhere save in times of spate. Beyond it lies the suburb of the Mercadal, surrounded by fortifications which form an integral part of the defences of the city. The river Ter, coming from the west, joins the Oña at the north side of the Mercadal and washes the extreme north-western corner of the walls of the city proper. The two heights upon whose lower slopes Gerona is built are separated from each other by a deep ravine, called the Galligan, down which run an intermittent watercourse and a road, the only one by which approach to the city from the east is possible. The northern height is crowned by the strong fort of Monjuich, the most formidable part of the city defences, with its three outlying redoubts called San Narciso, San Luis and San Daniel. The crest of the southern height is covered in a similar fashion by the three forts of the Capuchins, Queen Anne, and the Constable, with the Calvary redoubt lower down the slope above the Galligan, facing San Daniel on the other side of the ravine. Two other small fortifications, the redoubts of the ‘Chapter’ and the ‘City,’ cover the path which leads down from the forts to Gerona. Neither the Monjuich nor the Capuchin heights are isolated hills; each is the end of a spur running
  • 59. down from the higher mountains. But while the southern summit rises high above the hilly reach which joins it to the mountain of Nuestra Señora de los Angeles, the northern summit (where lies Monjuich) is at the end of a plateau extending far to the north. The Capuchin heights, therefore, can only be attacked uphill, while Monjuich can be assailed from ground of a level little inferior to itself. But except on this point both heights are very strong, their slopes being in many places absolutely precipitous, especially towards the Galligan, and everywhere steep. Nevertheless there are winding paths leading up both, from Sarria and Pont-Mayor in the case of Monjuich, from Casa de Selva and other villages towards the east and the sea in the case of the Capuchin heights. All the ground is bare rock, with no superincumbent soil. All the fortifications were somewhat antiquated in type, nothing having been done to modernize the defences since the war of the Spanish Succession[23] . Ferdinand VI and Charles III had neglected Gerona in favour of the new fortress of Figueras, nearer to the frontier, on which large sums had been expended—for the benefit of the French who seized it by treachery in 1808, and were now using it as their base of operations. The actual wall of enceinte of the city was mediaeval—a plain rampart twenty-five feet high, too narrow for artillery and set thickly with small towers; only at its two ends, on the Oña and the Ter, two bastions (called those of La Merced and Santa Maria) had been inserted, and properly armed. This weakness of the walls went for little so long as Monjuich, the Capuchins, and the other forts held firm, since the enemy could only approach the town-enceinte at its two ends, where the bastions lay. Far more dangerous was the feebleness of the Mercadal, whose ramparts formed the southern section of the exterior defences of the place. Its circuit had five plain bastions, but no demi-lunes or other outer defences, no covered way nor counterscarp: its profile, only some eighteen or twenty feet high, was visible, across the flat ground which surrounds it, from the foot to the summit of the wall, for want of ditch or glacis. The ground leading up to it was favourable for siege approaches, since the soil was soft and easy to dig, and was
  • 60. seamed with hollow roads and stone walls, giving much cover to an assailant. Aware of the defects of the fortifications of the Mercadal, the Spaniards had prepared a line of defence behind it, along the further bank of the Oña. They had made the river-front of the city proper defensible to a certain extent, by building up the doors and windows of all the houses which abut upon the water, mining the two bridges, and fixing a stockade and entanglements in the bed of the Oña, along the considerable space, where it is fordable in dry weather[24] . They had indeed repaired the whole circuit of the defences since Duhesme’s sieges of 1808, having cleared out the ditches of Monjuich and of the bastions of La Merced and Santa Maria, walled up many posterns, and repaired with new and solid masonry all the parts of the walls that had been dilapidated at the moment of the first siege. They had also pulled down many isolated houses outside the walls, and demolished the nearer half of the suburban village of Pedret, which lies (most inconveniently for the defence) along the bank of the Ter between the water and the slopes of Monjuich. All these precautions must be put to the credit of the governor, Mariano Alvarez de Castro, a man to be mentioned with all honour and respect, and probably the best soldier that Spain produced during the whole Peninsular War. He was a veteran of the Revolutionary and Portuguese wars, and had a good reputation, but no special credit for military science, down to the moment when he was put to the test. He had been the officer in charge of the castle of Barcelona on the occasion when it was seized by Duhesme in March 1808: his spirit had been deeply wounded by that vile piece of treachery, and he had at once adhered to the national cause. Since then he had been serving in the Ampurdam against Reille, till the moment when he was appointed governor of Gerona. Alvarez is described by those who served under him as a severe, taciturn man of a puritan cast of mind. ‘I should call him,’ wrote one of his brigadiers, ‘an officer without the true military talents, but with an extreme confidence in Providence—almost, one might say, a believer in miracles. His soul was great, capable of every sacrifice, full of
  • 61. admirable constancy; but I must confess that his heroism always seemed to me that of a Christian martyr rather than of a professional soldier[25] .’ General Fournas, who wrote this somewhat depreciatory sketch of his chief, was one of those who signed the capitulation while Alvarez was moaning no quiero rendirme on his sick-bed, so that his judgement is hardly to be taken as unprejudiced; but his words point the impression which the governor left on his subordinates. The details of his defence sufficiently show that he was a skilful and resourceful as well as an obstinate general. His minute care to utilize every possible means of defence prove that he was no mere waiter on miracles. That he was a very devout practising Catholic is evident from some of his doings; at the opening of the siege a great religious ceremony was held, at which the local patron saint, Narcissus, was declared captain of the city and presented with a gold-hilted sword. The levy en masse of the citizens was called ‘the Crusade,’ and their badge was the red cross. The ideas of religion and patriotism were so closely intertwined that to the lay companies of this force were afterwards added two clerical companies, one composed of monks and friars, the other of secular priests: about 200 of these ecclesiastics were under arms[26] . Even the women were organized in squads for the transport of wounded, the care of the hospitals, and the carrying of provisions to the soldiery on the walls: about 300 served, under the command of Donna Lucia Fitzgerald and Donna Maria Angela Bibern, wives of two officers of the regiment of Ultonia. Five of this ‘company of St. Barbara’ were killed and eleven wounded during the siege. The garrison at the moment of Verdier’s first attack consisted of about 5,700 men, not including the irregulars of the Crusade. There were seven battalions of the old army, belonging to the regiments of Ultonia[27] , Borbon, and Voluntarios de Barcelona, with three battalions of miqueletes, two local corps, 1st and 2nd of Gerona, and the 1st of Vich. Of cavalry there was a single squadron, newly levied, the ‘escuadron de San Narciso.’ Of artillery there were but 278 men, a wholly insufficient number: the officers of that arm were given 370 more to train, partly miqueletes of the 2nd Gerona battalion, partly
  • 62. sailors having some small experience of gunnery. It was difficult to make proper use of the great store of cannon in the fortress, when more than half the troops allotted to them had never before seen, much less served, a heavy gun of position. To the above 5,700 men of all arms must be added about 1,100 irregulars of the ‘Crusade’— seven lay and two clerical companies of fusiliers and two more of artificers. But these were set to guard almost unapproachable parts of the wall, or held in reserve: most of the stress fell upon the organized troops. The defence was altogether conducted on scientific principles, and had nothing in common with that of Saragossa. Here the irregulars formed only a small fraction of the garrison[28] , and were never hurled in senseless fury against the French batteries, but used carefully and cautiously as an auxiliary force, capable of setting free some part of the trained men for service on the more important points of the enceinte[29] . For the first two months of the siege Alvarez received no help whatever from without: in May the central government of Catalonia had been left in a perfectly paralysed condition, when Blake went off himself and took with him the best of the regular troops, in order to engage in the campaign of Alcañiz and Maria. Coupigny, the interim commander at Tarragona, had only 6,000 organized men, and he and the Catalan provincial junta were during that month much engrossed with an enterprise which distracted them from the needs of Gerona. A wide-spread conspiracy had been formed within the walls of Barcelona, with the object of rising against the garrison in St. Cyr’s absence. A secret committee of priests, merchants, and retired officers had collected all the arms in the city, smuggled in many muskets from without, and enlisted several thousand persons in a grand design for an outbreak and a sort of ‘Sicilian Vespers’ fixed—after two postponements—for the 11th of May. They opened communication with Coupigny and with the captains of the British frigates blockading the port. The one was to bring his troops to the gates, the others to deliver an attack on the port, upon the appointed night. No Spaniard betrayed the plot, though 6,000 citizens are said to have been in the secret, but it was frustrated by
  • 63. two foreigners. Conscious that the town could not be freed if the citadel of Monjuich was retained by the French, the conspirators sounded two Italian officers named Captain Dottori, fort adjutant of Monjuich, and Captain Provana, who was known to be discontented and thought to be corruptible. They offered them an immense bribe —1,000,000 dollars, it is said—to betray the postern of Monjuich to the troops of Coupigny, who were to be ready in the ditch at midnight. But they had mistaken their men: the officers conferred with Duhesme, and consented to act as agents provocateurs: they pretended to join the conspiracy, were introduced to and had interviews with the chiefs, and informed the governor. On the morning before the appointed date many of the leaders were arrested. Duhesme placed guards in every street, and proclaimed that he knew all. The citizens remained quiet in their despair, the chiefs who had not been seized fled, and the troops on the Llobregat retired to Tarragona. Duhesme hanged his captives, two priests named Gallifa and Pou, a young merchant named Massana, Navarro an old soldier, and four others. ‘They went to the gallows,’ says Vacani, an eye-witness, ‘with pride, convinced every one of them that they had done the duty of good citizens in behalf of king, country, and religion[30] .’ Engrossed in this plot, the official chiefs of Catalonia half forgot Gerona, and did nothing to help Alvarez till long after the siege had begun. The only assistance that he received from without was that the miqueletes and somatenes of the Ampurdam and the mountain region above Hostalrich were always skirmishing with Verdier’s outposts, and once or twice cut off his convoys of munitions on their way from Figueras to the front. The French engineers were somewhat at variance as to the right way to deal with Gerona. There were two obvious alternatives. An attack on the weak front of the Mercadal was certain to succeed: the ground before the walls was suitable for trenches, and the fortifications were trifling. But when a lodgement had been made in this quarter of the town it would be necessary to work forward, among the narrow lanes and barricades, to the Oña, and then to
  • 64. cross that river in order to continue similar operations through the streets of Gerona. Even when the city had been subdued, the garrison might still hold out in the formidable works on the Monjuich and Capuchin heights. The reduction of the Mercadal and the city, moreover, would have to be carried out under a continuous plunging fire from the forts above, which overlooked the whole place. This danger was especially insisted upon by some of the engineer officers, who declared that it would be impossible for the troops to work their way forward over ground so exposed. As a matter of fact it was proved, after the siege was over and the forts had been examined by the captors, that this fear had been exaggerated; the angle of fire was such that large sections of the town were in no way commanded from the heights, and the streets could not have been searched in the fashion that was imagined. But this, obvious in December, could not have been known in May[31] . The second alternative was to commence the attack on Gerona not from the easiest but from the most difficult side, by battering the lofty fort of Monjuich from the high plateau beside it. The defences here were very formidable: the ground was bare exposed rock: but if Monjuich were once captured it was calculated that the town must surrender, as it was completely overlooked by the fort, and had no further protection save its antiquated mediaeval wall. The deduction that it would be cheaper in the end to begin with the difficult task of taking Monjuich, rather than the easier operations against the Mercadal, seemed plausible: its fault was that it presupposed that Alvarez and his garrison would behave according to the accepted rules of siegecraft, and yield when their situation became hopeless. But in dealing with Spanish garrisons the rules of military logic did not always act. Alvarez essayed the impossible, and held out behind his defective defences for four months after Monjuich fell. The loss of men and time that he thereby inflicted on the French was certainly no less than that which would have been suffered if the besiegers had begun with the Mercadal, and worked upwards by incessant street fighting towards the forts on the height. But it is hard to say that Verdier erred: he did not know his adversary, and he did know, from his experiences at Saragossa, what street fighting meant.
  • 65. It may be added that Verdier’s views were accepted by the engineer-general, Sanson, who had been specially sent from France by the Emperor, to give his opinion on the best mode of procedure. The document which Verdier, Sanson, and Taviel (the commanding artillery officer of the 7th Corps) sent to Paris, to justify their choice of the upper point of attack, lays stress mainly on the impossibility of advancing from the Mercadal under the fire of the upper forts[32] . But there were other reasons for selecting Monjuich as the point of attack. It lay far nearer to the road to France and the central siege- dépôts beside Sarria and the Pont Mayor. The approaches would be over highly defensible ground where, if a disaster occurred, the defeated assailant could easily recover himself and oppose a strong front to the enemy. The shortness of the front was suitable for an army of the moderate strength of 14,000 men, which had to deal with a fortress whose perimeter, allowing for outlying forts and inaccessible precipices, was some six miles. Moreover, the ground in front of the Mercadal had the serious inconvenience of being liable to inundation; summer spates on the Ter and Oña are rare, but occur from time to time; and there was the bare chance that when the trenches had been opened all might be swept away by the rivers[33] . Verdier’s opinion was arrived at after mature reflection: the French had appeared in front of Gerona on May 8: the outlying villages on the east had been occupied between the twelfth and eighteenth: Lecchi’s Italians had closed the western exits by occupying the plain of Salt on the twenty-fourth: the inner posts of observation of the Spaniards had been cleared off when, on May 30, the Italians seized the suburban village of Santa Eugenia, and on June 1 the Germans took possession of the mountain of Nuestra Señora de los Angeles. But it was only on June 6 that the besiegers broke ground, and commenced their trenches and batteries on the plateau of Monjuich. It was necessary to make a beginning by subduing the outer defences of the fort, the towers or redoubts of San Luis, San Narciso, and San Daniel: two batteries of 24-pounders were constructed against them, while a third battery of mortars on
  • 66. the ‘Green Mound’ by the Casa den Roca on the west bank of the Ter, was to play upon the north end of the town: Verdier hoped that the bombardment would break the spirit of the citizens—little knowing the obstinate people with whom he had to deal. Five thousand bombs thrown into the place in June and July produced no effect whatever. More batteries on the heights were thrown up upon the 13th and 15th of June, while on the former day, to distract the attention of the Spaniards, Lecchi’s division, in the plain below, was ordered to open a false attack upon the Mercadal. This had good effect as a diversion, since Alvarez had expected an assault in this quarter, and the long line of trenches thrown up by the Italians in front of Santa Eugenia attracted much of his attention. Three days of battering greatly damaged San Luis and San Narciso, which were no more than round towers of masonry with ditches cut in the rock, and only two or three guns apiece. The French also took possession on the night of the fourteenth and fifteenth of the remains of the half- destroyed suburb of Pedret, between Monjuich and the Ter, as if about to establish themselves in a position from which they could attack the low-lying north gate of the town and the bastion of Santa Maria. Hitherto the defence had seemed a little passive, but at dawn on the morning of the seventeenth Alvarez delivered the first of the many furious sallies which he made against the siege lines. A battalion of Ultonia rushed suddenly down-hill out of Monjuich and drove the French, who were taken completely by surprise, out of the ruins of Pedret. Aided by a smaller detachment, including the artificers of the Crusade, who came out of the Santa Maria gate, they destroyed all the works and lodgements of the besiegers in the suburb, and held it till they were driven out by two French and one Westphalian battalion sent up from Verdier’s reserves. The Spaniards were forced back into the town, but retired in good order, contented to have undone three days of the besiegers’ labour. They had lost 155 men, the French 128, in this sharp skirmish. Two days later the towers of San Luis and San Narciso, which had been reduced to shapeless heaps of stone, were carried by assault,
  • 67. with a loss to the French of only 78 men; but an attempt to carry San Daniel by the same rush was beaten off, this redoubt being still in a tenable state. Its gorge, however, was completely commanded from the ruins of San Luis, and access to or exit from it was rendered so dangerous that Alvarez withdrew its garrison on the next night. The possession of these three outworks brought the French close up to Monjuich, which they could now attack from ground which was favourable in every respect, save that it was bare rock lacking soil. It was impossible to excavate in it, and all advances had to be made by building trenches (if the word is not a misnomer in this case) of sandbags and loose stones on the surface of the ground. The men working at the end of the sap were therefore completely exposed, and the work could only proceed at a great expense of life. Nevertheless the preparations advanced rapidly, and on the night of July 2 an enormous battery of sandbags (called the Batterie Impériale) was thrown up at a distance of only four hundred yards from Monjuich. Next morning it opened on the fort with twenty 16- and 24-pounders, and soon established a superiority over the fire of the defence. Several Spanish pieces were dismounted, others had to be removed because it was too deadly to serve them. But a steady fire was returned against the besiegers from the Constable and Calvary forts, on the other side of the Galligan ravine. Nevertheless Monjuich began to crumble, and it looked as if the end of the siege were already approaching. On July 3 there was a breach thirty-five feet broad in the fort’s north-eastern bastion, and the Spanish flag which floated over it was thrown down into the ditch by a chance shot. A young officer named Montorro climbed down, brought it up, and nailed it to a new flagstaff under the fire of twenty guns. Meanwhile long stretches of the parapet of Monjuich were ruined, the ditch was half-filled with débris, and the garrison could only protect themselves by hasty erections of gabions and sandbags, placed where the crest of the masonry had stood. By this time St. Cyr and the covering army had abandoned the position in the plain of Vich which they had so long occupied. The general had, as it seems, convinced himself at last that Blake, who
  • 68. was still engaged in his unlucky Aragonese campaign, was not likely to appear. He therefore moved nearer to Gerona, in order to repress the efforts of the local somatenes, who were giving much trouble to Verdier’s communications. On June 20 he established his head quarters at Caldas de Malavella, some nine miles to the south-east of Gerona. That same evening one of his Italian brigades intercepted and captured a convoy of 1,200 oxen which the Governor of Hostalrich was trying to introduce into the beleaguered city along one of the mountain-paths which lead to the Capuchin heights from the coast. St. Cyr strung out his 14,000 men in a line from San Feliu de Guixols on the sea to the upper Ter, in a semicircle which covered all the approaches to Gerona saving those from the Ampurdam. He visited Verdier’s camp, inspected the siege operations, and expressed his opinion that an attack on the Mercadal front would have been preferable to that which had been actually chosen. But he washed his hands of all responsibility, told Verdier that, since he had chosen to correspond directly with Paris, he must take all the praise or blame resulting from his choice, and refused to countermand or to alter any of his subordinate’s dispositions. On July 2 however he sent, with some lack of logic, a summons of his own to Alvarez, inviting him to surrender on account of the desperate state of his defences: this he did without informing Verdier of his move. The Governor returned an indignant negative, and Verdier wrote in great wrath to complain that if the siege was his affair, as he had just been told, it was monstrous that his commander should correspond with the garrison without his knowledge[34] . The two generals were left on even worse terms than before. St. Cyr, however, gave real assistance to the siege operations at this time by storming, on July 5, the little fortified harbour-town of Palamos, which lies on the point of the sea- coast nearest to Gerona, and had been hitherto used by the miqueletes as a base from which they communicated by night with the fortress, and at the same time kept in touch with Tarragona and the English ships of the blockading squadron. On the night of the 4th and 5th of July the defences of Monjuich appeared in such a ruinous condition that Commandant Fleury, the
  • 69. engineer officer in charge of the advanced parallel, took the extraordinary and unjustifiable step of assaulting them at 10 p.m. with the troops—two companies only—which lay under his orders, trusting that the whole of the guards of the trenches would follow if he made a lodgement. This presumptuous attack, made contrary to all the rules of military subordination, was beaten off with a loss of forty men. Its failure made Verdier determine to give the fort three days more of continuous bombardment, before attempting to storm it: the old batteries continued their fire, a new one was added to enfilade the north-western bastion, and cover was contrived at several points to shelter the troops which were to deliver the assault, till the actual moment of the storm arrived[35] . But three hundred yards of exposed ground still separated the front trenches from the breach—a distance far too great according to the rules of siegecraft. The Spaniards meanwhile, finding it impossible under such a fire to block the breach, which was now broad enough for fifty men abreast[36] , threw up two walls of gabions on each side of it, sank a ditch filled with chevaux-de-frise in front of it, and loopholed some interior buildings of the fort, which bore upon its reverse side. Monjuich, however, looked in a miserable state when, just before sunrise on July 7, Verdier launched his columns of assault upon it. He had collected for the purpose the grenadier and voltigeur companies of each of the twenty French, German, and Italian battalions of the besieging army, about 2,500 men in all[37] . They were divided into two columns, the larger of which went straight at the breach, while the smaller, which was furnished with ladders, was directed to escalade the left face of the demi-lune which covers the northern front of Monjuich. The troops passed with no great loss over the open space which divided them from the work, as its guns had all been silenced, and the fire from the more distant forts was ineffective in the dusk. But when they got within close musketry range they began to fall fast; the head of the main column, which was composed of some sapper companies and the Italian Velites of the Guard, got up on to the face of the breach, but could never break in. Every officer or man who reached the cutting and its
  • 70. chevaux-de-frise was shot down; the concentric fire of the defenders so swept the opening that nothing could live there. Meanwhile the rear of the column was brought to a stand, partly in, partly outside, the ditch. The Spaniards kept playing upon it with musketry and two or three small 2- and 4-pounders, which had been kept under cover and reserved for that purpose, firing canister into it at a distance of twenty or thirty yards. Flesh and blood could not bear this for long, and the whole mass broke and went to the rear. Verdier, who had come out to the Batterie Impériale to view the assault, had the men rallied and sent forward a second time: the head of the column again reached the breach, and again withered away: the supporting mass gave way at once, and fell back much more rapidly than on the first assault. Yet the General, most unwisely, insisted on a third attack, which, made feebly and without conviction, by men who knew that they were beaten, only served to increase the casualty list. Meanwhile the escalade of the demi-lune by the smaller column had been repelled with ease: the assailants barely succeeded in crossing the ditch and planting a few ladders against the scarp: no one survived who tried to mount them, and the troops drew off. This bloody repulse cost the French 1,079 casualties, including seventy-seven officers killed or wounded—much more than a third of the troops engaged. It is clear, therefore, that it was not courage which had been lacking: nor could it be said that the enemy’s artillery fire had not been subdued, nor that the breach was insufficient, nor that the 300 yards of open ground crossed by the column had been a fatal obstacle; indeed, they had been passed with little loss. The mistake of Verdier had been that he attacked before the garrison was demoralized—the same error made by the English at Badajoz in 1811 and at San Sebastian in 1813. A broad breach by itself does not necessarily make a place untenable, if the spirit of the defenders is high, and if they are prepared with all the resources of the military art for resisting the stormers, as were the Geronese on July 7-8. The garrison lost, it may be remarked, only 123 men, out of a strength of 787 present in the fort that morning. The casualty list, however, was somewhat increased by the
  • 71. accidental explosion, apparently by a careless gunner, of the magazine of the tower of San Juan, alongside of the Galligan, which was destroyed with its little garrison of twenty-five men. The repulse of the assault of Monjuich thoroughly demoralized the besieging army: the resistance of the Spaniards had been so fierce, the loss they had inflicted so heavy, that Verdier’s motley collection of French, German, Lombard, and Neapolitan regiments lost heart and confidence. Their low spirits were made manifest by the simultaneous outbreak of desertion and disease, the two inevitable marks of a decaying morale. All through the second half of July and August the hospitals grew gradually fuller, not only from sunstroke cases (which were frequent on the bare, hot, rocky ground of the heights), but from dysentery and malaria. The banks of the Ter always possessed a reputation for epidemics—twice in earlier centuries a French army had perished before the walls of Gerona by plagues, which the citizens piously attributed to their patron, San Narciso. It was mainly because he realized the depression of his troops that Verdier refrained from any more assaults, and went on from July 9 to August 4 battering Monjuich incessantly, while he cautiously pushed forward his trenches, till they actually reached the ditch of the demi-lune which covers the northern front of the fort. The garrison was absolutely overwhelmed by the incessant bombardment, which destroyed every piece of upstanding masonry, and prevented them from rebuilding anything that was demolished. They were forced to lurk in the casemates, and to burrow for shelter in the débris which filled the interior of the work. Three large breaches had been made at various points, yet Verdier would never risk another assault, till on August 4 his approaches actually crowned the lip of the ditch of the demi-lune, and his sappers had blown in its counterscarp. The ruined little outwork was then stormed with a loss of only forty men. This put the French in the possession of good cover only a few yards from the main body of the fort. Proceeding with the same caution as before, they made their advances against Monjuich by mining: on the night of the 8th–9th August no less than twenty-three mines
  • 72. under the glacis of the fort were exploded simultaneously. This left a gaping void in front of the original breach of July 7, and filled up the ditch with débris for many yards on either side: part of the interior of the fort was clearly visible from the besiegers’ trenches. Only one resource for saving Monjuich remained to Alvarez—a sortie for the expulsion of the enemy from their advanced works. It was executed with great courage at midday on August 9, while at the same time separate demonstrations to distract the enemy were made at two other points. The column from Monjuich had considerable success; it stormed two advanced batteries, spiked their guns, and set fire to their gabions; the French were cleared out of many of their trenches, but made head behind one of the rear batteries, where they were joined by their reserves, who finally thrust back the sallying force into the fort. The damage done, though considerable, could be repaired in a day. Verdier gave orders for the storm of the dilapidated fort on the night of August 11, and borrowed a regiment from St. Cyr’s covering army to lead the assault, being still very doubtful of the temper of his own troops. But at six on the preceding afternoon an explosion was heard in Monjuich, and great part of its battered walls flew up into the air. The Spaniards had quietly evacuated it a few minutes before, after preparing mines for its demolition. The French, when they entered, found nothing but a shapeless mass of stones and eighteen disabled cannon. The garrison had lost, in the sixty-five days of its defence, 962 men killed and wounded; the besiegers had, first and last, suffered something like three times this loss. While the bombardment of Monjuich was going on, the Spanish generals outside the fortress had at last begun to make serious efforts for its assistance. Not only had the somatenes redoubled their activity against Verdier’s convoys, and several times succeeded in destroying them or turning them back, but Coupigny had at last begun to move, for he saw that since Blake’s rout at Belchite on June 18 he, and he alone, possessed an organized body of troops on this side of Spain, small though it was. Unable to face St. Cyr in the field, he tried at least to throw succours into Gerona by the
  • 73. mountain paths from the south, if he could do no more. The first attempt was disastrous: three battalions started from Hostalrich under an English adventurer, Ralph Marshall, whom Alvarez had suggested for the command of this expedition. They evaded the first line of the covering army, but at Castellar, on July 10, ran into the very centre of Pino’s division, which had concentrated from all sides for their destruction. Marshall escaped into Gerona with no more than twelve men: 40 officers and 878 rank and file laid down their arms; the rest of the column, some 600 or 700 men, evaded surrender by dispersion[38] . Equally disastrous, though on a smaller scale, was another attempt made on August 4 by a party of 300 miqueletes to enter Gerona: they eluded St. Cyr, but on arriving at the entry of the Galligan, close under the forts, made the unfortunate mistake of entering the convent of San Daniel, which the garrison had been compelled to evacuate a few days before. It was now in the French lines, and the Catalans were all taken prisoners. It was not till August 17, six days after the fall of Monjuich, that Alvarez obtained his first feeble reinforcement: the miquelete battalion of Cervera, with a draft for that of Vich already in the garrison, altogether 800 bayonets, got into the city on the west side, by eluding Lecchi’s Italians in the plain and fording the Ter. They were much needed, for Alvarez was complaining to the Catalan Junta that he had now only 1,500 able-bodied men left of his original 5,000[39] . Verdier had written to his master, after the capture of Monjuich, to announce that Gerona must infallibly surrender within eight or ten days[40] , now that it had nothing but an antiquated mediaeval wall to oppose to his cannon. So far, however, was he from being a true prophet that, as a matter of fact, the second and longer episode of the siege, which was to be protracted far into the winter, had only just begun.
  • 74. SECTION XVII: CHAPTER III THE FALL OF GERONA. AUGUST–DECEMBER, 1809 When Monjuich had been evacuated, the position of Gerona was undoubtedly perilous: of the two mountain summits which command the city one was now entirely in the hands of the French; for not only the great fort itself but several of the smaller works above the ravine of the Galligan—such as the fortified convent of San Daniel and the ruined tower of San Juan—had been lost. The front exposed to attack now consisted of the northern section of the old city wall, from the bastion of Santa Maria at the water’s edge, to the tower of La Gironella, which forms the north-eastern angle of the place, and lies further up the slope of the Capuchin heights than any other portion of the enceinte. The space between these two points was simply covered by a mediaeval wall set with small round towers: neither the towers nor the curtain between them had been built to hold artillery. Indeed the only spots on this front where guns had been placed were (1) the comparatively modern bastion of Santa Maria, (2) a work erected under and about the Gironella, and called the ‘Redoubt of the Germans,’ and (3, 4) two parts of the wall called the platforms[41] of San Pedro and San Cristobal, which had been widened till they could carry a few heavy guns. On the rest of the enceinte, owing to its narrowness, nothing but wall-pieces and two- pounders could be mounted. The parts of the curtain most exposed to attack were the sections named Santa Lucia, San Pedro, San Cristobal, and Las Sarracinas, from churches or quarters which lay close behind them. With nothing but an antiquated wall, seven to nine feet thick, thirty feet high, and destitute of a ditch, it seemed that this side of Gerona was doomed to destruction within a few days.
  • 75. But there were points in the position which rendered the attack more difficult than might have been expected. The first was that any approaches directed against this front would be exposed to a flanking fire from the forts on the Capuchin heights, especially from the Calvary and Chapter redoubts. The second was that the greater part of the weak sections of the wall were within a re-entering angle; for the tower of Santa Lucia and the ‘Redoubt of the Germans’ by the Gironella project, and the curtains between them are in a receding sweep of the enceinte. Attacks on these ill-fortified sections would be outflanked and enfiladed by the two stronger works. The only exposed part of the curtain was that called Santa Lucia, running from the tower of that name down to the bastion of Santa Maria. Lastly, the parallels which the French might construct from their base on Monjuich would have to be built on a down slope, overlooked by loftier ground, and when they reached the foot of the walls they would be in a sort of gulley or bottom, into which the defenders of the city could look down from above. The only point from which the north end of Gerona could be approached from flat ground and without disadvantages of slope, is the short front of less than 200 yards breadth between the foot of Monjuich and the bank of the Ter. Here, in the ruins of the suburb of Pedret, there was plenty of cover, a soil easy to work, and a level terrain as far as the foot of the Santa Maria bastion. The engineers of the besieging army selected three sections of wall as their objective. The first was the ‘Redoubt of the Germans’ and the tower of La Gironella, the highest and most commanding works in this part of the enceinte: once established in these, they could overlook and dominate the whole city. The other points of attack were chosen for the opposite reason —because they were intrinsically weak in themselves, not because they were important or dominating parts of the defences. The curtain of Santa Lucia in particular seemed to invite attack, as being in a salient angle, unprotected by flanking fire, and destitute of any artillery of its own. Verdier, therefore, on the advice of his engineers, set to work to attack these points of the enceinte between La Gironella and Santa
  • 76. Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookultra.com