Learning to Program in Perl

Total Page:16

File Type:pdf, Size:1020Kb

Learning to Program in Perl Learning to Program in Perl by Graham J Ellis Languages of the Web Learning to Program in Perl version 1.7 Written by Graham Ellis [email protected] Design by Lisa Ellis Well House Consultants, Ltd. 404, The Spa, Melksham, Wiltshire SN12 6QL England +44 (0) 1225 708 225 (phone) +44 (0) 1225 707 126 (fax) Find us on the World Wide Web at: http://www.wellho.net Or contact us at: [email protected] Copyright © 2003 by Well House Consultants, Ltd. Printed in Great Britain. Printing History May 1999 1.0 First Edition February 2000 1.1 Minor additions June 2000 1.2 Compliation of modules October 2000 1.3 Name change, revisions April 2002 1.4 Added modules September 2002 1.5 Added modules January 2003 1.6 Updated modules February 2003 1.7 Updated modules This manual was printed on 21 May 2003. Notice of Rights All rights reserved. No part of this manual, including interior design, may be reproduced or translated into any language in any form, or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without prior written permission of Well House Consultants except in the case of brief quotations embodied in critical articles and reviews. For more information on getting permission for reprints and excerpts, contact Graham Ellis at Well House Consultants. This manual is subject to the condition that it shall not, by way of trade or otherwise, be lent, sold, hired out or otherwise circulated without the publisher's prior consent, incomplete nor in any form of binding or cover other than in which it is published and without a similar condition including this condition being imposed on the subsequent receiver. Notice of Liability All brand names and product names used in this book are trade names, service marks, trademarks or registered trademarks of their respective owners. Well House Consultants is not associated with any product or vendor in this book and where such designations appear in this book, and Well House Consultants was aware of a trademark claim, the designa- tions have been appropriately capitalised. Well House Consultants cannot attest to the accuracy of this information and use of a term should not be regarded as affecting the validity of any trademark or service mark. The information in this book is distributed on an "as is" basis, without warranty. Whilst every precaution has been taken in the preparation of this manual, neither the author nor Well House Consultants assumes responsibility for errors or omissions, nor shall be liable to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described herein. Table of Contents 1Introduction . 9 1.1 What is Perl? . 9 1.2 Perl Platforms . 11 1.3 Perl Versions . 11 1.4 Examples of Perl in use . 15 2Hello Perl World. 17 2.1 Let's study a first program. 17 2.2 Summary . 21 Exercise . 22 3Variables and Operations . 23 3.1 Reading from the user . 23 3.2 More about variables . 24 3.3 How do I do calculations?. 27 3.4 Summary . 29 Exercise . 30 4Perl Fundamentals. 31 4.1 First Perl program . 31 4.2 Comments and documentation. 32 4.3 Summary . 38 Exercise . 38 4.4 Reading data . 39 4.5 Summary . 42 Exercise . 42 5 More about the Perl Environment . 43 5.1 Integrating your program with your computer . 43 5.2 Unix and Linux systems . 43 5.3 Windows 98, 2000 and Windows NT systems . 45 5.4 MS-DOS users . 47 5.5 Macintosh . 47 5.6 The compiler and the interpreter. 47 5.7 Some questions on compilers and interpreters . 48 5.8 Debugging tools . 49 5.9 Summary . 51 Exercise . 52 6 Conditionals and Loops . 53 6.1 The "if" statement . 53 6.2 The "while" statement . 54 6.3 Shorthand operators . 56 6.4 Ways of writing numbers . 59 6.5 Summary . 59 Exercise . 60 Learning to Program in Perl 3 Contents 7 Analysing a Programming Task. 61 7.1 A small job . 61 Exercise . 67 7.2 As a job gets larger. 67 7.3 Summary . 71 Exercise . 72 8Initial String Handling . 73 8.1 String handling functions . 73 8.2 String handling operators . 74 8.3 Comparing strings exactly . 76 8.4 Comparing strings to regular expressions . 77 8.5 Summary . 83 Exercise . 84 9 More Loops and Conditionals . 85 9.1 The variety that is Perl . 85 9.2 More conditional statements. 85 9.3 More loop statements . 89 9.4 Breaking a loop. 90 9.5 Labels . 91 9.6 The goto statement. 92 9.7 Summary . 93 Exercise . 94 10 File Handling . 95 10.1 File input and output . 95 10.2 File testing . 99 10.3 Formatted printing. 100 10.4 Summary . 103 Exercise . 104 11 Lists . 105 11.1 Basics . 105 11.2 The length of a list . 107 11.3 Context . 108 11.4 Summary . 110 Exercise . 111 11.5 Functions that operate on lists . 112 11.6 Iterating through a list . 114 11.7 List slices . 116 11.8 Anonymous lists . 117 11.9 Summary . 117 Exercise . 118 12 Subroutines in Perl . 119 12.1 What are subroutines and why? . 119 12.2 Calling a subroutine . 121 12.3 Writing your own subroutine . 123 12.4 Writing subroutines in a separate file . 125 12.5 Scope . 127 Exercise . 130 12.6 packages . 131 12.7 Calling objects . 134 4 Well House Consultants Contents 12.8 Writing a class – an introduction. 136 13 Special Variables . 137 13.1 The Command line . 137 13.2 Information variables . 138 13.3 Behaviour changing variables. 139 13.4 The default input and pattern match space . 141 13.5 More options on Perl's command line. 143 13.6 Others . 143 13.7 Summary . 144 Exercise . 144 14 Hashes . 145 14.1 Setting up a hash . 145 14.2 Accessing a hash . 146 14.3 Processing every element of a hash. 147 14.4 Ordering a hash (sorting) . 149 14.5 Programming techniques . 153 14.6 Special hashes . 156 14.7 Summary . ..
Recommended publications
  • How to Secure Your Web Site Picked up SQL Injection and Cross-Site Scripting As Sample Cases of Failure Because These Two Are the Two Most Reported Vulnerabilities
    How to Secure your Website rd 3 Edition Approaches to Improve Web Application and Web Site Security June 2008 IT SECURITY CENTER (ISEC) INFORMATION-TECHNOLOGY PROMOTION AGENCY, JAPAN This document is a translation of the original Japanese edition. Please be advises that most of the references referred in this book are offered in Japanese only. Both English and Japanese edition are available for download at: http://www.ipa.go.jp/security/english/third.html (English web page) http://www.ipa.go.jp/security/vuln/websecurity.html (Japanese web page) Translated by Hiroko Okashita (IPA), June 11 2008 Contents Contents ......................................................................................................................................... 1 Preface ........................................................................................................................................... 2 Organization of This Book ........................................................................................................... 3 Intended Reader ......................................................................................................................... 3 Fixing Vulnerabilities – Fundamental Solution and Mitigation Measure - .................................... 3 1. Web Application Security Implementation ............................................................................... 5 1.1 SQL Injection .................................................................................................................... 6 1.2
    [Show full text]
  • Red Hat Enterprise Linux 8 Installing, Managing, and Removing User-Space Components
    Red Hat Enterprise Linux 8 Installing, managing, and removing user-space components An introduction to AppStream and BaseOS in Red Hat Enterprise Linux 8 Last Updated: 2021-06-25 Red Hat Enterprise Linux 8 Installing, managing, and removing user-space components An introduction to AppStream and BaseOS in Red Hat Enterprise Linux 8 Legal Notice Copyright © 2021 Red Hat, Inc. The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/ . In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version. Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law. Red Hat, Red Hat Enterprise Linux, the Shadowman logo, the Red Hat logo, JBoss, OpenShift, Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries. Linux ® is the registered trademark of Linus Torvalds in the United States and other countries. Java ® is a registered trademark of Oracle and/or its affiliates. XFS ® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries. MySQL ® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
    [Show full text]
  • Hacker Public Radio
    hpr0001 :: Introduction to HPR hpr0002 :: Customization the Lost Reason hpr0003 :: Lost Haycon Audio Aired on 2007-12-31 and hosted by StankDawg Aired on 2008-01-01 and hosted by deepgeek Aired on 2008-01-02 and hosted by Morgellon StankDawg and Enigma talk about what HPR is and how someone can contribute deepgeek talks about Customization being the lost reason in switching from Morgellon and others traipse around in the woods geocaching at midnight windows to linux Customization docdroppers article hpr0004 :: Firefox Profiles hpr0005 :: Database 101 Part 1 hpr0006 :: Part 15 Broadcasting Aired on 2008-01-03 and hosted by Peter Aired on 2008-01-06 and hosted by StankDawg as part of the Database 101 series. Aired on 2008-01-08 and hosted by dosman Peter explains how to move firefox profiles from machine to machine 1st part of the Database 101 series with Stankdawg dosman and zach from the packetsniffers talk about Part 15 Broadcasting Part 15 broadcasting resources SSTRAN AMT3000 part 15 transmitter hpr0007 :: Orwell Rolled over in his grave hpr0009 :: This old Hack 4 hpr0008 :: Asus EePC Aired on 2008-01-09 and hosted by deepgeek Aired on 2008-01-10 and hosted by fawkesfyre as part of the This Old Hack series. Aired on 2008-01-10 and hosted by Mubix deepgeek reviews a film Part 4 of the series this old hack Mubix and Redanthrax discuss the EEpc hpr0010 :: The Linux Boot Process Part 1 hpr0011 :: dd_rhelp hpr0012 :: Xen Aired on 2008-01-13 and hosted by Dann as part of the The Linux Boot Process series.
    [Show full text]
  • Perl DBI API Reference
    H Perl DBI API Reference This appendix describes the Perl DBI application programming interface. The API consists of a set of methods and attributes for communicating with database servers and accessing databases from Perl scripts. The appendix also describes MySQL-specific extensions to DBI provided by DBD::mysql, the MySQL database driver. I assume here a minimum version of DBI 1.50, although most of the material applies to earlier versions as well. DBI 1.50 requires at least Perl 5.6.0 (with 5.6.1 preferred). As of DBI 1.611, the minimum Perl version is 5.8.1. I also assume a minimum version of DBD::mysql 4.00. To determine your versions of DBI and DBD::mysql (assuming that they are installed), run this program: #!/usr/bin/perl # dbi-version.pl - display DBI and DBD::mysql versions use DBI; print "DBI::VERSION: $DBI::VERSION\n"; use DBD::mysql; print "DBD::mysql::VERSION: $DBD::mysql::VERSION\n"; If you need to install the DBI software, see Appendix A , “Software Required to Use This Book.” Some DBI methods and attributes are not discussed here, either because they do not apply to MySQL or because they are experimental methods that may change as they are developed or may even be dropped. Some MySQL-specific DBD methods are not discussed because they are obsolete. For more information about new or obsolete methods, see the DBI or DBD::mysql documentation, available at http://dbi.perl.org or by running the following commands: % perldoc DBI % perldoc DBI::FAQ % perldoc DBD::mysql The examples in this appendix are only brief code fragments.
    [Show full text]
  • 2016 8Th International Conference on Cyber Conflict: Cyber Power
    2016 8th International Conference on Cyber Conflict: Cyber Power N.Pissanidis, H.Rõigas, M.Veenendaal (Eds.) 31 MAY - 03 JUNE 2016, TALLINN, ESTONIA 2016 8TH International ConFerence on CYBER ConFlict: CYBER POWER Copyright © 2016 by NATO CCD COE Publications. All rights reserved. IEEE Catalog Number: CFP1626N-PRT ISBN (print): 978-9949-9544-8-3 ISBN (pdf): 978-9949-9544-9-0 CopyriGHT AND Reprint Permissions No part of this publication may be reprinted, reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of the NATO Cooperative Cyber Defence Centre of Excellence ([email protected]). This restriction does not apply to making digital or hard copies of this publication for internal use within NATO, and for personal or educational use when for non-profit or non-commercial purposes, providing that copies bear this notice and a full citation on the first page as follows: [Article author(s)], [full article title] 2016 8th International Conference on Cyber Conflict: Cyber Power N.Pissanidis, H.Rõigas, M.Veenendaal (Eds.) 2016 © NATO CCD COE Publications PrinteD copies OF THIS PUBlication are availaBLE From: NATO CCD COE Publications Filtri tee 12, 10132 Tallinn, Estonia Phone: +372 717 6800 Fax: +372 717 6308 E-mail: [email protected] Web: www.ccdcoe.org Head of publishing: Jaanika Rannu Layout: Jaakko Matsalu LEGAL NOTICE: This publication contains opinions of the respective authors only. They do not necessarily reflect the policy or the opinion of NATO CCD COE, NATO, or any agency or any government.
    [Show full text]
  • A Java Virtual Machine Extended to Run Parrot Bytecode
    A JAVA VIRTUAL MACHINE EXTENDED TO RUN PARROT BYTECODE A thesis submitted to the University of Manchester for the degree of Master of Science in the Faculty of Engineering and Physical Sciences 2006 By Martin Dahl School of Computer Science Contents Abstract 8 Declaration 9 Copyright 10 Acknowledgements 11 1 Introduction 12 1.1 Objectives and Motivation . 13 1.2 Related Work . 13 1.2.1 Parrot . 14 1.2.2 Pugs . 14 1.2.3 PearColator . 14 1.3 Organisation of the Thesis . 15 2 The Parrot Project 16 2.1 Perl 6 . 17 2.1.1 Design . 17 2.1.2 Perl 6 Internals . 18 2.1.3 Pugs . 19 2.1.4 Parrot Perl 6 Compiler . 19 2.2 Virtual Machine . 20 2.2.1 Design . 20 2.2.2 Architecture . 21 2.2.3 Registers . 22 2.2.4 Instruction Set . 23 2.2.5 Parrot Assembly Language and Intermediate Representation 24 2 2.3 Parrot Magic Cookies . 24 2.3.1 Core PMCs . 24 2.3.2 Other PMCs . 27 2.4 Compiler suite . 27 2.4.1 Perl 6 . 27 2.4.2 Other languages . 27 2.5 Summary . 28 3 Parrot Bytecode Format 30 3.1 Header . 31 3.2 Bytecode Format 1 . 33 3.2.1 Directory Segment . 34 3.2.2 Constant Table Segment . 35 3.2.3 Bytecode Segment . 38 3.2.4 Debug Segment . 38 3.2.5 Fixup Segment . 39 3.3 Summary . 40 4 Parakeet 41 4.1 Overview . 42 4.2 Jikes RVM . 43 4.3 PearColator .
    [Show full text]
  • Interfacing Apache HTTP Server 2.4 with External Applications
    Interfacing Apache HTTP Server 2.4 with External Applications Jeff Trawick Interfacing Apache HTTP Server 2.4 with External Applications Jeff Trawick November 6, 2012 Who am I? Interfacing Apache HTTP Server 2.4 with External Applications Met Unix (in the form of Xenix) in 1985 Jeff Trawick Joined IBM in 1990 to work on network software for mainframes Moved to a different organization in 2000 to work on Apache httpd Later spent about 4 years at Sun/Oracle Got tired of being tired of being an employee of too-huge corporation so formed my own too-small company Currently working part-time, coding on other projects, and taking classes Overview Interfacing Apache HTTP Server 2.4 with External Applications Jeff Trawick Huge problem space, so simplify Perspective: \General purpose" web servers, not minimal application containers which implement HTTP \Applications:" Code that runs dynamically on the server during request processing to process input and generate output Possible web server interactions Interfacing Apache HTTP Server 2.4 with External Applications Jeff Trawick Native code plugin modules (uhh, assuming server is native code) Non-native code + language interpreter inside server (Lua, Perl, etc.) Arbitrary processes on the other side of a standard wire protocol like HTTP (proxy), CGI, FastCGI, etc. (Java and \all of the above") or private protocol Some hybrid such as mod fcgid mod fcgid as example hybrid Interfacing Apache HTTP Server 2.4 with External Applications Jeff Trawick Supports applications which implement a standard wire protocol, no restriction on implementation mechanism Has extensive support for managing the application[+interpreter] processes so that the management of the application processes is well-integrated with the web server Contrast with mod proxy fcgi (pure FastCGI, no process management) or mod php (no processes/threads other than those of web server).
    [Show full text]
  • Threat Modeling and Circumvention of Internet Censorship by David Fifield
    Threat modeling and circumvention of Internet censorship By David Fifield A dissertation submitted in partial satisfaction of the requirements for the degree of Doctor of Philosophy in Computer Science in the Graduate Division of the University of California, Berkeley Committee in charge: Professor J.D. Tygar, Chair Professor Deirdre Mulligan Professor Vern Paxson Fall 2017 1 Abstract Threat modeling and circumvention of Internet censorship by David Fifield Doctor of Philosophy in Computer Science University of California, Berkeley Professor J.D. Tygar, Chair Research on Internet censorship is hampered by poor models of censor behavior. Censor models guide the development of circumvention systems, so it is important to get them right. A censor model should be understood not just as a set of capabilities|such as the ability to monitor network traffic—but as a set of priorities constrained by resource limitations. My research addresses the twin themes of modeling and circumvention. With a grounding in empirical research, I build up an abstract model of the circumvention problem and examine how to adapt it to concrete censorship challenges. I describe the results of experiments on censors that probe their strengths and weaknesses; specifically, on the subject of active probing to discover proxy servers, and on delays in their reaction to changes in circumvention. I present two circumvention designs: domain fronting, which derives its resistance to blocking from the censor's reluctance to block other useful services; and Snowflake, based on quickly changing peer-to-peer proxy servers. I hope to change the perception that the circumvention problem is a cat-and-mouse game that affords only incremental and temporary advancements.
    [Show full text]
  • LAMP and the REST Architecture Step by Step Analysis of Best Practice
    LAMP and the REST Architecture Step by step analysis of best practice Santiago Gala High Sierra Technology S.L.U. Minimalistic design using a Resource Oriented Architecture What is a Software Platform (Ray Ozzie ) ...a relevant and ubiquitous common service abstraction Creates value by leveraging participants (e- cosystem) Hardware developers (for OS level platforms) Software developers Content developers Purchasers Administrators Users Platform Evolution Early stage: not “good enough” solution differentiation, innovation, value flows Later: modular architecture, commoditiza- tion, cloning no premium, just speed to market and cost driven The platform effect - ossification, followed by cloning - is how Chris- tensen-style modularity comes to exist in the software industry. What begins as a value-laden proprietary platform becomes a replaceable component over time, and the most successful of these components finally define the units of exchange that power commodity networks. ( David Stutz ) Platform Evolution (II) Example: PostScript Adobe Apple LaserWriter Aldus Pagemaker Desktop Publishing Linotype imagesetters NeWS (Display PostScript) OS X standards (XSL-FO -> PDF, Scribus, OOo) Software Architecture ...an abstraction of the runtime elements of a software system during some phase of its oper- ation. A system may be composed of many lev- els of abstraction and many phases of opera- tion, each with its own software architecture. Roy Fielding (REST) What is Architecture? Way to partition a system in components
    [Show full text]
  • Perl Variables Scalar ($) Array (@) Hash (%)
    Practical Extraction and Report Language « Perl is a language of getting your job done » « There is more than one way to do it » Larry Wall VI, October 2006 Page 1 Perl Outline : History Structure of a simple Perl script Perl variables scalar ($) array (@) hash (%) Operators (numeric, string & logical) Statement modifiers (if/elsif/else, for/foreach, while) VI, October 2006 Page 2 Practical Extraction and Report Language http://perl.oreilly.com " Perl is both a programming language and an application on your computer that runs those programs " VI, October 2006 Page 3 Perl history A few dates: 1969 UNIX was born at Bell Labs. 1970 Brian Kernighan suggested the name "Unix" and the operating system we know today was born. 1972 The programming language C is born at the Bell Labs (C is one of Perl's ancestors). 1973 “grep” is introduced by Ken Thompson as an external utility: Global REgular expression Print. 1976 Steven Jobs and Steven Wozniak found Apple Computer (1 April). 1977 The computer language awk is designed by Alfred V. Aho, Peter J. Weinberger, and Brian W. Kernighan (awk is one of Perl's ancestors). VI, October 2006 Page 4 Perl history 1987 Perl 1.000 is unleashed upon the world NAME perl | Practical Extraction and Report Language SYNOPSIS perl [options] filename args DESCRIPTION Perl is a interpreted language optimized for scanning arbitrary text files, extracting information from those text files, and printing reports based on that information. It's also a good language for many system management tasks. The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal).
    [Show full text]
  • OTRS Developer Manual Release 8.0
    OTRS Developer Manual Release 8.0 OTRS AG Jul 08, 2020 Contents 1 Getting Started 3 1.1 Development Environment ..................................... 3 1.1.1 Obtain the Source Code .................................. 3 1.1.2 Useful Tools ......................................... 3 1.1.3 Linking Expansion Modules ................................ 4 1.2 Architecture Overview ........................................ 4 1.2.1 Directories .......................................... 7 1.2.2 Files ............................................. 7 1.2.3 Core Modules ........................................ 7 1.2.4 Front End Handle ...................................... 8 1.2.5 Front End Modules ..................................... 8 1.2.6 CMD Front End ....................................... 8 1.2.7 Generic Interface Modules ................................. 8 1.2.8 Scheduler Task Handler Modules ............................. 9 1.2.9 Database .......................................... 10 2 OTRS Internals - How it Works 11 2.1 Config Mechanism .......................................... 11 2.1.1 Defaults.pm: OTRS Default Configuration ...................... 11 2.1.2 Automatically Generated Configuration Files ....................... 11 2.1.3 XML Configuration Files .................................. 11 2.1.4 Accessing Config Options at Runtime .......................... 20 2.2 Database Mechanism ........................................ 21 2.2.1 SQL ............................................. 21 2.2.2 XML ............................................
    [Show full text]
  • Intermediate Perl
    SECOND EDITION Intermediate Perl Randal L. Schwartz, brian d foy, and Tom Phoenix Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo Intermediate Perl, Second Edition by Randal L. Schwartz, brian d foy, and Tom Phoenix Copyright © 2012 Randal Schwartz, brian d foy, Tom Phoenix. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Editors: Simon St. Laurent and Shawn Wallace Indexer: Lucie Haskins Production Editor: Kristen Borg Cover Designer: Karen Montgomery Copyeditor: Absolute Service, Inc. Interior Designer: David Futato Proofreader: Absolute Service, Inc. Illustrator: Rebecca Demarest March 2006: First Edition. August 2012: Second Edition. Revision History for the Second Edition: 2012-07-20 First release See http://oreilly.com/catalog/errata.csp?isbn=9781449393090 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Intermediate Perl, the image of an alpaca, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein.
    [Show full text]