27,99 €
Everything beginners need to start programming with Perl Perl is the ever-popular, flexible, open source programming language that has been called the programmers' Swiss army knife. This book introduces Perl to both new programmers and experienced ones who are looking to learn a new language. In the tradition of the popular Wrox Beginning guides, it presents step-by-step guidance in getting started, a host of try-it-out exercises, real-world examples, and everything necessary for a Perl novice to start programming with confidence. * Introduces Perl to both new programmers and experienced ones who want to learn a new language * Provides a host of real-world applications for today's environments so readers can get started immediately * Covers the new features of Perl but fully applicable to previous editions Beginning Perl provides the information and instruction you need to confidently get started with Perl. For Instructors: Classroom and training support material are available for this book.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 956
Veröffentlichungsjahr: 2012
CONTENTS
Chapter 1: What is Perl?
Perl Today
Getting Perl
The Perl Community
Using perldoc
Using a Terminal Window
Creating Hello, World!
Summary
Chapter 2: Understanding the CPAN
CPAN and METACPAN
CPAN Clients
Summary
Chapter 3: Variables
What is Programming?
A Few Things to Note Before Getting Started
Scalars
Arrays
Hashes
Slices
Context
Scope
Strict, Warnings, and Diagnostics
Perl’s Built-in Variables
Summary
Chapter 4: Working With Data
Using Scalars
Array and List Functions
Built-in Hash Functions
Scoping Keywords
Summary
Chapter 5: Control Flow
Using the if Statement
for/foreach loops
Using while/until Loops
Statement Modifiers
given/when
Summary
Chapter 6: References
References 101
Working with References
Summary
Chapter 7: Subroutines
Subroutine Syntax
Returning Data
FAIL!
Subroutine References
Prototypes
Recursion
Things to Watch For
Summary
Chapter 8: Regular Expressions
Basic Matching
Advanced Matching
Common Regular Expression Issues
Summary
Chapter 9: Files and Directories
Basic File Handling
Directories
Unicode
Useful Modules
Summary
Chapter 10: Sort, Map, and Grep
Basic Sorting
map and grep
Putting It All Together
Summary
Chapter 11: Packages and Modules
Namespaces and Packages
Subroutines in Other Packages
BEGIN, UNITCHECK, CHECK, INIT, and END
Plain Old Documentation (POD)
Creating and Installing Modules
Summary
Chapter 12: Object Oriented Perl
What Are Objects? The Ævar the Personal Shopper
Three Rules of Perl OO
Objects – Another View
A Brief Recap
Gotchas
Summary
Chapter 13: Moose
Understanding Basic Moose Syntax
Advanced Moose Syntax
Moose Best Practices
Summary
Chapter 14: Testing
Basic Tests
Understanding Test::More Test Functions
Using Other Testing Modules
Understanding xUnit Style Using Testing
Summary
Chapter 15: The Interwebs
A Brief Introduction to HTTP
Web Clients
Summary
Chapter 16: Databases
Using the DBI
Selecting Basic Data
Summary
Chapter 17: Plays Well With Others
The Command Line
Other Programs
Summary
Chapter 18: Common Tasks
Using CSV Data
Understanding Basic XML
Handling Dates
Understanding Your Program
Summary
Chapter 19: The Next Steps
What Next?
Understanding Object-Relational Mappers
Using the Template Toolkit
Using Catalyst to Build Apps
Summary
Appendix: Answers To Exercises
Introduction
Advertisements
WHAT YOU WILL LEARN IN THIS CHAPTER:
Getting Perl
Learning about the community
Understanding the Perl documentation
Using a terminal
Writing your first Hello, World! program
My goodness, where to start? To even begin to cover a language with such a rich history and huge influence over the world of computing and the web is a daunting task, so this chapter just touches on the highlights.
By the time you finish with this chapter, you’ll have a good understanding of the history of Perl and where to go to get more help when you need to know more than this book offers. Learning how to find the answers to your questions is probably one of the most valuable skills you can develop.
Before you install Perl, a word about Perl terminology — information that you need to know to converse intelligently with other Perl users.
The name of the language is Perl. It is not PERL. Larry Wall, the creator of Perl, originally wanted a name with positive connotations and named the language Pearl, but before its release, he discovered another programming language named Pearl, so he shortened the name to Perl.
The name of the language causes a bit of confusion. When people write Perl (uppercase), they are referring to the programming language you learn in this book. When people write perl (lowercase), they are referring to the binary executable used to run Perl, the language.
So perl is the binary and Perl is the language. The former parses and runs the latter: perl parses and runs Perl. If someone writes PERL, you know immediately that they’re not familiar with the Perl language. This is why sometimes you see experienced programmers use PERL to refer to poorly written Perl programs.
Due to the wording of the original documentation that shipped with Perl, many programmers assume that PERL is an acronym for Practical Extraction and Report Language. However perlfaq1 — the documentation that shipped with Perl — sets the record straight:
... never write "PERL", because perl is not an acronym, apocryphal folklore and post-facto expansions notwithstanding.
Remember, there is no such thing as PERL. It’s Perl, the language, or perl, the executable.
Today, Perl is widely used throughout the world. It comes standard on every major operating system apart from Windows and is still extensively used in web development, thus driving many websites. New startups choose Perl as their language of choice for data processing, system administration, web development, and other uses.
As of this writing, Ricardo Signes, a long time Perl hacker, is overseeing the development of Perl. Perl 6, a new language with roots in Perl 5, is being actively worked on with several interesting implementations, including a Niecza, which runs on Mono/.NET.
This book mostly focuses on 5.8.x and 5.10.x versions of Perl, even though support for both of these has officially been discontinued. Why? This was a difficult decision to make, but there were several reasons for this decision. An important consideration is that surveys show most businesses still run these versions of Perl. It’s a strange thing for a book author to stand up and say, “This book targets an unsupported version of the language,” but you go to war with the Perl you have, not the Perl you want.
Fortunately, this choice isn’t as bad as it might sound. The Perl 5 Porters (known as “P5P”) work hard to keep new releases of Perl backward compatible. Perl 5.14.2 ships with almost half a million tests (455,832, to be exact) to ensure that Perl works exactly as intended. Thus, what you learn to write throughout this book generally works unmodified on later versions of Perl.
Obviously, it’s difficult to program Perl if you don’t have it installed on your computer; this section covers several methods for doing this. Even if you already have Perl installed, you should to read this section anyway because if your system depends on your Perl installation, you might want to install a separate version to avoid changing behavior that your system requires.
So how do you get Perl? Well, you’re in luck. Almost every major operating system aside from Windows ships with Perl by default. This is often referred to as the system Perl. You can test whether you already have Perl installed by opening up a terminal and typing perl -v at the command line. Currently, on my MacBook Pro, this prints the following:
$ perl -v This is perl 5, version 14, subversion 2 (v5.14.2) built for darwin-2level Copyright 1987-2011, Larry Wall Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit. Complete documentation for Perl, including FAQ lists, should be found on this system using "man perl" or "perldoc perl". If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page.
Perl is supported on more than 100 platforms — did you even know there were that many? If you want a different version of Perl than what you already have installed, go to http://www.perl.org/get.html.
If you do not run Windows, check out perlbrew (http://www.perlbrew.pl/). This tool enables you to install multiple and run different versions of Perl.
Running different Perl installations is important because there’s a good chance that some of your operating system depends on the behavior of the system Perl. Therefore, using perlbrew to install your own versions of Perl not only ensures that you don’t need to worry about breaking your system Perl, but you also can play with different versions.
That being said, so long as you’re not overwriting any modules that your system Perl uses, it’s fine to use your system Perl for learning Perl. It’s also usually fine to upgrade your system modules, but it’s not recommended. If a core module your system depends on changes in an incompatible way, the results are unpredictable. Windows does not have this problem because it does not depend on Perl.
If your system has both bash and curl installed, you can try to install perlbrew with the following command-line command:
curl -kL http://xrl.us/perlbrewinstall | bash
If you don’t have curl installed but you do have wget, you can install perlbrew with this:
wget --no-check-certificate -O - http://install.perlbrew.pl | bash
If that works on your system, it should enable you to easily install multiple versions of Perl without superuser (root, or administrator) permissions. It’s then easy to switch between those versions. This has many benefits, including the following:
It’s easy to try new versions of Perl.
You don’t risk breaking your system’s Perl.
You don’t need superuser permission to install
Comprehensive Perl Archive Network
(CPAN) modules.
You can test production code on newer versions of Perl.
To install and use Perl version 5.14.2, type the following (but see the perlbrew available command below):
perlbrew install perl-5.14.2 perlbrew switch perl-5.14.2
The installation takes a while because perlbrew needs to download and build the version of Perl you’re asking for.
After perlbrew installs, you can use the following commands:
perlbrew help:
Typing
perlbrew help
shows you how to use
perlbrew
. It’s quite easy.
Installing an older Perl version:
If you want to install an older version of Perl, you can run the following:
perlbrew install perl-5.8.3
Switching versions:
You can run
perlbrew list
to see which versions of Perl you have installed and can switch to a different version. Following is the author’s setup:
$ perlbrew list perl-5.10.1 perl-5.12.3 perl-5.14.0 * perl-5.14.2 perl-5.8.3
Testing code:
To test your code against different versions of Perl, use the following:
perlbrew exec myprogram.pl
Available versions:
As of this writing, following are the Perl versions available to install on the author’s computer. The
perlbrew available
command lists all available versions:
$ perlbrew available perl-5.15.4 i perl-5.14.2 perl-5.12.4 i perl-5.10.1 perl-5.8.9 perl-5.6.2 perl5.005_04 perl5.004_05 perl5.003_07
If you can use perlbrew, it will make your programming life much more pleasant.
TABLE 1.1: perldoc Tutorials
TUTORIAL
DESCRIPTION
perlreftut
Tutorial on references
perldsc
Data structures cookbook
perllol
Data structures: arrays of arrays
perlrequick
Regular expression quickstart
perlretut
Regular expression tutorial
perlboot
Object Oriented (OO) Perl for beginners
perltoot
OO tutorial, part 1
perltooc
OO tutorial, part 2
perlbot
OO tricks and examples
perlstyle
Style guide
perlcheat
Cheat sheet
perltrap
Traps for the unwary
perldebtut
Debugger tutorial
Windows is one of the few operating systems that does not include Perl by default. This makes things a bit more difficult, but you have a wide variety of options here. Your author recommends Strawberry Perl, but ActivePerl is also an excellent choice. Cygwin is only recommended only if you want a Linux emulation layer.
Strawberry Perl (http://strawberryperl.com) is the newest option for Windows, but it’s the one many developers prefer today. It’s also free and it’s the choice of Perl that Larry Wall utilizes when he uses Windows. Strawberry Perl does not offer commercial support. Like many open source projects, support is excellent — but on a volunteer basis.
When you install Strawberry Perl, the following software is installed with it:
Mingw GCC C/C++ compiler
dmake
make
tool
ExtUtils::CBuilder
and
ExtUtils::ParseXS
Bundle::CPAN
Bundle::LWP
(which provides more reliable HTTP CPAN repository support)
XML::Parser
and
XML::LibXML
, which enables most CPAN XML modules
DBI and DBD drivers for SQLite, ODBC, MySQL, and Postgres
Additional minor modules to enhance the stability of Win32 Perl.
Don’t worry about what all this means for now. As you move further along in the book, these items will start to make sense. Just know that they make Perl on Windows easy enough to use that it rivals Perl on Linux for many tasks. Unless you have a particular reason to use another version of Perl, the author recommends Strawberry Perl. Some things to remember with Strawberry Perl follow:
Pros:
Strawberry Perl “just works.” Almost everything you need to develop Perl is bundled with it, including many tools that are usually mandatory in a work environment.
Cons:
It’s relatively new and companies that rely on Windows are sometimes uncomfortable with software that lacks commercial support.
Another strong alternative for Windows is ActivePerl (http://www.activestate.com/activeperl). It’s free, but commercial support is provided. ActivePerl has been available for more than a decade and is probably the most popular Perl for Windows. When considering ActivePerl, remember the following:
Pros:
ActivePerl has been around for more than a decade, and it is maintained by a company with a strong history of supporting Perl and dynamic languages. It’s also often updated faster than Strawberry Perl. Additionally, some binary packages are easier to install with ActiveState than with Strawberry Perl.
Cons
: ActivePerl does not ship with the full set of tools with which Strawberry Perl ships. Further, it contains some non-open source utilities and, unlike Strawberry Perl, it cannot be embedded in other open source projects.
One way to run Perl on Windows is to install Cygwin, a free Linux emulator for Windows. You can download Cygwin from http://www.cygwin.com/. Click the Install Cygwin link for instructions.
By default, Cygwin does not install Perl. You can easily find instructions on the web for installing and running Perl under Cygwin, including many useful YouTube videos. If you go this route, make sure that when you install Cygwin, you select both Perl and the GCC/C++ packages from Development menu when you’re given a choice on which packages to install. However, to get the most out of Perl on Cygwin, make sure you have the following packages installed:
perl
gcc/C++
gnupg
gzip
lynx
make
ncftp
ncftpget
tar
unzip
wget
This list should cover most of what you need. Keep the following in mind:
Pros:
With Cygwin, you get a Linux environment, which means that most Perl programs can run unchanged.
Cons:
As an emulation layer, it tends to be a bit slow. It’s also a bit difficult to install everything correctly if you’re not used to it.
You didn’t read detailed instructions on how to install Perl for Windows or how to install alternative versions of Perl on your operating system of choice. As mentioned previously, Perl is supported on more than 100 platforms, and although the author has tried writing instructions on how to do this in the past, the impossibility of handling that obscure error that someone inevitably has makes this difficult. Fortunately, Perl is easy to install on Windows, and the language has a strong community supporting it; this community can help you work through even the most unusual issues.
Because the Wrox “Programmer to Programmer” series targets experienced developers looking to expand their skills, you, the developer, will likely be familiar with software installation. If you’re new to programming, you might need a bit more help. Either way, the following sections discuss a variety of resources to help you start.
Internet Relay Chat (IRC) has been around since 1988, and it’s often a great way to get questions answered “in real time.” With IRC, you have several options:
mIRC (
http://www.mirc.net/
):
For Windows, this is probably the most popular IRC client, but it’s shareware, and you can use it only for 30 days before paying.
KVIrc (
http://www.kvirc.net/
):
This is a good, free choice for a graphical IRC client, and it’s available for most platforms.
Colloquy (
http://colloquy.info/
):
For OS X, the author uses this.
Chatzilla (
http://chatzilla.hacksrus.com/
):
If you use the Firefox browser, it has the capable Chatzilla add-on, which this should work regardless of which operating system you choose.
freenode:
You can also access
freenode
with any browser via
http://webchat.freenode.net/
.
Actually, any IRC client you’re comfortable with is fine.
When you get on IRC, connect to the irc.freenode.net server and join #perl. The #perl channel generally has plenty of users, and you can get many Perl questions answered quickly and easily — or at least get told where to RTFM, which stands for Read The Manual. (the “F” is silent.)
If you’re not familiar with IRC, hit you favorite search engine and search for list of IRC commands. You can also consult the Wikipedia page for IRC (http://en.wikipedia.org/wiki/Irc) for more information, including lists of other IRC clients.
PerlMonks (http://www.perlmonks.org/) is a fantastically useful Perl site that’s been around for more than a decade. Your author joined in 2000, unsurprisingly as “Ovid,” and has been a regular contributor for years.
In the top right corner of the site, you see many useful links. Seekers of Perl Wisdom is probably the most useful when you need an answer to a problem. When you first post a question, it shows in Newest Nodes, and many people follow that to try to help answer the new questions. Fortunately, the regular users at PerlMonks generally don’t suffer as much from the “first post” silliness you often find at other sites.
In addition to answering questions, PerlMonks has book reviews, Meditations (a section for people who just want to muse about Perl-related things), tutorials, Perl news, site discussion, and a chatterbox for those who just want casual conversation or have a quick question.
If you’re serious about learning Perl, PerlMonks is a good place to start. Many of the top minds in Perl hang out there, and it’s a good resource with plenty of history to search through. PerlMonks is “all Perl, all the time.” Joe Bob says, “Check it out.”
For those who like a bit of real-life interaction (and who doesn’t?), there’s also Perl Mongers (http://www.pm.org/). Founded by brian d foy in 1997, Perl Mongers is an organization of Perl hackers in different cities who meet periodically to, well, do whatever they want. Your author ran the Perl Mongers group in Portland, Oregon (Portland.pm) for several years, and has attended Perl Mongers meetings in a number of countries.
The local Perl Mongers user groups are Perl enthusiasts who enjoy hanging out together and talking about stuff. Sometimes that stuff is Perl. The Portland.pm group generally schedules technical talks followed by a “social” at a local pub, often the excellent Lucky Lab in Portland, Oregon. If you ever visit Portland, check out that pub.
There are Perl Mongers groups on every continent except Antarctica, but there was discussion of an Antarctica group starting up when Mongers found out there was a Perl programmer there. If you live near a major city, there’s a good chance there’s a Perl Mongers group close to you. If not, create one!
StackOverflow (http://stackoverflow.com/) was created in 2008 by Joel Spolsky and Jeff Atwood as an “open” site for anyone to ask programming-related questions. It has spun off numerous related sites and has become extremely popular as the site where you can ask just about any technology question.
Perl questions are answered quickly with solid information, and you can easily see the “rating” of the users who respond to your questions. Because of how questions are tagged, it’s easy to quickly drill down to questions that might be relevant to your situation.
Now that you’ve installed Perl, the first thing you should do is get acquainted with the extensive Perl documentation that ships with the language. As this book covers various topics, a perldoc tip often prefixes sections, like this:
perldoc perlnumber
If you type perldoc perlnumber into your terminal, you receive an introduction to how numbers are used in Perl. If you prefer a web browser, go to http://perldoc.perl.org/, select your Perl version, and then go to: http://perldoc.perl.org/perlnumber.html.
By constantly reinforcing perldoc throughout this text, you get the tools to find answers to most questions yourself. This is one bit of advice the author would have liked to received when starting his Perl journey in the ‘90s. You don’t need to memorize the material in the documentation, but as you become more familiar with it, you’ll find it easier to remember where to look it up later.
The Perl documentation is written in POD, short for Plain Old Documentation. POD is an easy-to-learn markup language for documenting Perl. It’s easy enough to learn (and you will in Chapter 11), but flexible enough, that many authors write their books in POD.
When you type perldoc<documentation name>, the program searches through parts of your system where it thinks the documentation may be found, looking for a file with a .pod or .pm extension. The .pod extension is preferred, and .pm is used if the file with the .pm extension has embedded POD and the .pod extension is not found. The program then formats the POD and displays it. For earlier versions of perldoc, you could add the -v switch to see where the perldoc command is looking for your POD:
perldoc -v perldoc
If your version of perldoc supports (see perldocperldoc) this, use the -D switch to see where perldoc is looking for the documentation. The -v switch now displays the description of Perl’s built-in variables:
perldoc -v '$_' perldoc -v '@ARGV'
You can also type perldoc perlvar to see all of Perl’s built-in variables.
You can read perldoc perldoc for more information about how to customize perldoc output or to see what other command-line switches it supports.
The first thing you want to do is type perldoc perl. This gives you a brief description of some of what Perl can do and quickly directs you to
perldoc perlintro
That’s a gentle introduction to Perl. If you’re dedicated, you could start there and not buy this or any other Perl book. That approach works if you have lots of time and patience. This book presents what you need to know most, including where to get more information.
The perlintro is clear but terse. It assumes that you already know how to program and rushes through the basic features of the language. As a result, there are many bits and pieces you should be aware of but won’t be. So to follow up on the perlintro, you’ll want:
perldoc perltoc
As you might expect, that’s the Table of Contents for the Perl documentation. For Perl 5.14.2, that Table of Contents is more than 20,000 lines! That’s a huge amount of documentation. It’s longer than many of the chapters in this book, and your author hopes his publisher doesn’t notice. In contrast, Perl 5.8.3’s Table of Contents weighs in at a measly 11,911 lines. However, this book mostly focuses on 5.8 and 5.10, and it won’t actually talk (much) about what’s in those newer documents.
Perl comes bundled with many tutorials you can read with perldoc. Table 1-1 lists the tutorials that are some of the popular ones included in Perl version 5.8.3. You can type perldoc<tutorialname> to read these tutorials.
Because the author had so much fun cutting and pasting from the documentation and padding the page count, Table 1-2 lists the Frequently Asked Questions (FAQs) that ship with Perl.
TABLE 1.2: perlfaq
FAQ
DESCRIPTION
perlfaq
Perl FAQs
perlfaq1
General questions about Perl
perlfaq2
Obtaining and learning about Perl
perlfaq3
Programming tools
perlfaq4
Data manipulation
perlfaq5
Files and formats
perlfaq6
Regexes (regular expressions)
perlfaq7
Perl language issues
perlfaq8
System interaction
perlfaq9
Networking
These FAQs are extensive. For example, the following are some of the questions addressed in perlfaq2:
What machines support Perl? Where do I get Perl?
How can I get a binary version of Perl?
I don’t have a C compiler on my system. How can I compile Perl?
I copied the Perl binary from one machine to another, but scripts don’t work. Why?
What’s nice is that for any of these questions, you can type perldoc -q “something I’m looking for” and perldoc will spit out the sections from any FAQ that matches the term you give it. (Actually, perldoc matches against regular expressions, which aren’t covering until Chapter 8, so pretend you didn’t read that bit.)
A full reference manual also ships with the Perl documentation along with extensive information about the internals of Perl (not for the faint of heart), linking Perl to C and C++ programs, platform-specific information, and other things that aren’t covered in this book.
One of the most useful perldoc commands is perldoc -f . When you type perldoc -f, followed by a function name, you can see a complete description of the function in question and quite possibly far more than you ever need to know. For example, perldoc -f my displays the following:
my EXPR my TYPE EXPR my EXPR : ATTRS my TYPE EXPR : ATTRS A "my" declares the listed variables to be local (lexically) to the enclosing block, file, or "eval". If more than one value is listed, the list must be placed in parentheses. The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE is currently bound to the use of the "fields" pragma, and attributes are handled using the "attributes" pragma, or starting from Perl 5.8.0 also via the "Attribute::Handlers" module. See "Private Variables via my()" in perlsub for details, and fields, attributes, and Attribute::Handlers.
It starts with the grammar for the function and then a brief (and sometimes verbose) explanation of that function. In the preceding example, the grammar could represent any of the following:
my $dog; my Dog $spot; my $dog : HasSpots; my Dog $spot : HasSpots;
You can skip this section if you already know how to use a terminal window. Otherwise, this section will explain the absolute minimum you need to know about opening and using a terminal window. As with a number of other languages, if you want to program in Perl, much of your professional life will be spent in a terminal window.
Perl comes from a UNIX background and, as a result, is often run from a terminal window. Unlike many graphical user interface (GUI) systems, terminals enable you to type commands directly into the system rather than clicking an icon on a screen or selecting items from menus. Getting used to the command line not only gives you all the power of a GUI system, but also leverages the considerable power of the command line. If you’re not familiar with this method, hit your favorite search engine for how to use the command line on your system, but for now, this section concentrates on getting a terminal window open.
This isn’t difficult, but ask a geek friend for help if you get stuck.
If you’re familiar with Linux, you probably already know about the terminal window. Unfortunately, because there are more than 100 Linux distributions and many different window managers, it’s impossible to tell you how to do this on your system. However, following are some general tips:
If you’re on a Mac, you can follow these steps:
A quick check of a search engine for mac command line or learning os x terminal should bring you up to speed on some of the basic commands. When you use the Mac command line, you’ll find that most standard UNIX/Linux commands operate the same way.
For Windows, you have a couple options:
If you’ve installed Cygwin, you can double-click the Cygwin desktop icon (not the installer!) and you’ll automatically be at a command-line prompt ready to go.
Press the Windows key and r at the same time. This should bring up a Run dialog box. Type
cmd
(short for command) into the box, click OK, and a terminal window pops up.
You can bring up the Run dialog box by clicking Start; then you should see Run as one of the menu items. Click that and it’s the same procedure: type
cmd
into that box and click OK.
If you don’t like the standard terminal on Windows, some people prefer console, available via free download at http://sourceforge.net/projects/console/.
For Windows, the terminal window is sometimes referred to as a DOS window. DOS stands for Disk Operating System and earlier versions of Windows were based on DOS with a Window manager on top. Today, Windows is a GUI system, and the DOS window is an emulation layer, but the commands have not changed much over time.
If you’re unfamiliar with the Windows command line, search the Internet for list of DOS commands to learn more about this environment.
Now that you have a terminal window open, you might want to find out where you are on your system. To see the current directory you are in, you can type pwd (print working directory) on Linux or OS X, or cd (with no arguments) on Windows. You can type ls on Linux or OS X to see a list of files in the current directory or dir if you’re on Windows.
Create a folder named wroxperl and change to it. For most major operating systems, type this:
mkdir wroxperl cd wroxperl
You should now be in an empty directory, suitable for creating your sample programs. When you create them, make them in separate directories named chapter1, chapter2, and so on. This makes it easier to organize and refer back to them. So go ahead and create a chapter1 directory now and change to it:
mkdir chapter1 cd chapter1
You won’t need this until you get to the “Hello, World!” section (it’s a law that all programming books start with this), but stay in the terminal for now to get used to the perldoc command.
Now that you’ve read far too much documentation (who am I kidding? You skimmed it), it is time for that traditional rite (write?) of passage, “Hello, World!” As one friend explained to me, he was proud that he could write “Hello, World!” in 15 programming languages — though he could program in none. Try to avoid that, okay?
First, open your terminal and type this:
perl -e 'print "Hello, Wrox!\n"'
Oh, wait. Sorry Windows people. You have to type this:
perl -e "print \"Hello, Wrox!\n\""
Except that it might not work, depending on your version of Windows. See perldoc perlfaq3 and read the section “Why don’t Perl one-liners work on my DOS/Mac/VMS system?” to understand why your life is difficult. If you have a Mac, the “Mac” section likely does not apply to you because OS X handles Perl and the command line quite well, thank you.
Aside from your author blatantly patronizing the publisher, the “Hello, Wrox!” snippet shows something common about Perl: running Perl from the command line. This won’t be covered much in the book, but as you get more familiar with Perl, you’ll see people doing things like this:
As you can see, using Perl on the command line effectively gives you a lot of power to get things done quickly. You can read perldoc perlrun to understand some of this, but search for perlone-liners online to see what you can do if you’re interested in this area.
Getting back to “Hello, World!”, the general way you write a Perl program is to save a file with the program code and then type perl<programname>. The first line of the program is often the shebang line, which you learn more about in a bit. After that is your program text. All you need to do to get a basic Perl program running is to type up your program, save it (usually with a .pl extension), and then type perl<programname>.
Listing 1-1 is a short Perl program that shows how a simple program may look. You learn more about the strict, warnings, and diagnostics in Chapter 3.
The first line of a Perl program often starts with a shebang line. A shebang line starts with “sharp” (#) and an exclamation point, also known as a “bang” (!), hence the term shebang. The line is followed by a path telling the shell where to find the interpreter that is used to execute the program.
On a system that understands the chmod command, you can type chmod +xprogramname to make the program directly executable. If it’s in your path, you can then type programname to run the program. Otherwise, you can type the full or relative path to the program to execute it.
For example, if you’re in /Users/ovid/wroxperl/chapter1 and you create a program called runme in that directory, you could run it like this:
$ ./runme $ /Users/ovid/wroxperl/chapter1/runme
For now, you can just type perlprogramname to run the programs.
The shebang line might take one of a number of different forms. On a Linux system, this often looks like one of the following:
#!/usr/bin/perl #!/usr/local/bin/perl #!/usr/bin/perl -w #!/usr/bin/env perl
The first two lines point directly to the Perl executable that should run the program. The third line, with the -w switch, tells Perl to run the program with global warnings. The final line tells Perl to use the env program to find out which perl is currently set as the default perl for your system. This is useful if you have different versions of Perl installed and want your program to always run with the Perl you’re currently using.
Some people just do the following:
#!/perl
And that generally does what you want.
On Windows you might see the following:
#!C:\Perl\bin\perl.exe #!C:\strawberry\perl\bin\perl.exe
The first line is often found when running with ActiveState Perl. The line version is found when running with Strawberry Perl.
When perl sees the shebang line, it attempts to run your program using whatever it finds after the #!. Generally, this isn’t a problem, but if you want to run the script on more than one machine, even with the same architecture, you could have a problem if someone installs Perl in a different location.
Fortunately, there is one simple trick you can follow to ensure you don’t have problems with shebang lines: Don’t install modules and scripts by hand. Instead, package them as proper distributions and install them with the standard Perl toolchain (such as cpan or cpanm). You learn module installation in Chapter 2 and module writing in Chapter 11.
For the Perl code that can be downloaded with this book, you will not be using shebang lines because they tend not to be portable. You will need to run the programs by explicitly typing perlprogramname.
By this time you’ve learned a bit about the history of Perl, where to go to get more information, installing Perl, and running a simple Perl program. This isn’t a huge amount of information, but it’s the foundation you need to progress in Perl.
TOPIC
KEY CONCEPTS
History
The basic history of the Perl language, its releases, and common use.
Getting Perl
About system Perl and
perlbrew
for those who use UNIX-style systems. Cygwin, ActivePerl, and Strawberry Perl are compared as options for Windows users.
Community
Perlmonks, IRC, Perl Mongers, and StackOverflow are all valuable resources for learning Perl.
perldoc
Perl comes with extensive documentation. You learned the basic structure of the docs and how to look up basic information.
Using a terminal
You use a terminal extensively when programming Perl. You learned how to launch a terminal and run a program from the command line.
WHAT YOU WILL LEARN IN THIS CHAPTER:
Understanding the CPAN
Using CPAN clients to install modules
This is the end of Chapter 10. Or it was. Many Perl books, if they include information about the Comprehensive Perl Archive Network(CPAN), mention it almost as an afterthought, just as your author was going to. However, CPAN is the soul of Perl. Its use is so common that your author repeatedly found it hard to create compelling examples of Perl without duplicating code already on the CPAN. Thus, the CPAN is now not only near the front of the book, it has an entire chapter all to itself. You cannot be a real Perl programmer without understanding the CPAN.
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
Lesen Sie weiter in der vollständigen Ausgabe!
