Perl 5 Essential Training

Perl 5 Essential Training

with Bill Weinman

 


In Perl 5 Essential Training, author Bill Weinman explains the fundamentals of programming in Perl, a flexible and powerful programming language that’s well suited for projects as varied as simple scripts to complex web applications. This course covers the details of the language, from conditionals, loops, and data structures to regular expressions, functions, and object-oriented programming. A quick-start guide is included for experienced developers who want to get up and running with Perl 5 fast. Exercise files are included with the course.
Topics include:
  • Understanding Perl's general syntax
  • Using data types effectively
  • Defining and calling subroutines
  • Modular and object-oriented programming
  • Prefix and postfix loops and conditionals
  • Performing math, manipulating strings, and working with complex data structures
  • Understanding regular expressions
  • Formatting code: best practices
  • Exploring the new features in Perl 5.10

show more

author
Bill Weinman
subject
Developer, Web, Programming Languages, Web Development
software
Perl 5
level
Intermediate
duration
6h 54m
released
Apr 23, 2010

Share this course

Ready to join? subscribe


Keep up with news, tips, and latest courses.

submit Course details submit clicked more info

Please wait...

Search the closed captioning text for this course by entering the keyword you’d like to search, or browse the closed captioning text by selecting the chapter name below and choosing the video title you’d like to review.



Introduction
Welcome
00:04Hi! I'm Bill Weinman, and I'd like to welcome you to Perl 5 Essential Training.
00:10Perl is a very flexible and powerful programming language that's well suited for
00:14a variety of projects, from simple scripts to complex web applications.
00:19In this course, I'll show you how to use Perl and how to take advantage of its
00:23unique and powerful features.
00:26I'll start by giving you an overview of Perl, so you can get started right away.
00:30This Perl Quick Start is designed for the experienced programmer who wants to
00:34leverage their existing knowledge to get up to speed with Perl quickly and with
00:39as little detail as necessary.
00:41Then we'll get right into the details of the language, syntax and
00:45structure, conditionals, loops, operators, data structures, subroutines,
00:51and regular expressions.
00:53I'll show you how to do common tasks in Perl including File I/O, databases, CGI
00:58and web development.
01:00And I'll show you how to use modules to leverage your work and the work of
01:04others to get your projects done faster, and with less effort.
01:08Finally, I'll walk you through some real-world examples of working Perl code,
01:12so you can see how the pieces fit together, and to help you get started on your own projects.
01:18This course is intended for users who already have some programming knowledge.
01:22If you have experience in at least one other modern programming language,
01:26this course is for you.
01:28I've been a programmer since the 70s, and I've been using Perl since the early 90s.
01:32I'm glad to be able to share the knowledge and experience I've gained along the
01:36way, so that you can write better applications today.
01:40Now let's get started with Perl 5 Essential Training.
Collapse this transcript
Using the exercise files
00:00If you are a premium member of the lynda.com Online Training Library, or if you
00:06are watching this tutorial on a DVD-ROM, you have access to the Exercise Files
00:10used throughout this title.
00:12I have copied the Exercise Files to my desktop, and I recommend that you do the
00:16same, or at least keep track of where you have put them, so that you know how to get at them.
00:21And the Exercise Files are organized by chapter, so we can see here Chapter 01,
00:26Chapter 02, Chapter 03 and so on.
00:30Throughout most of this title, we'll be using Eclipse, and we'll be accessing
00:35the Exercise Files from inside of Eclipse.
00:38And as we do so, we'll be making working copies of the individual files before
00:44we actually work on them.
00:46In this example, if I wanted to make a working file of this countlines.pl,
00:50I'm holding down the Option key on this Macintosh, or if you're on a PC
00:56running Windows, you would hold down the Ctrl key, or if you're on another
01:00operating system, you'll use whatever key it is that commonly copies files
01:04when you drag them.
01:06And I'm dragging it to the folder icon, because that just seems to be the most
01:10reliable way to do this in Eclipse.
01:12And when I let go of it, Eclipse will ask me for a new name, and I will say
01:17newname.pl and press the Return key on my keyboard.
01:22And then I'll work in that working copy, so that I don't overwrite the original
01:27file, and if I want to go back and the do the exercise again, I can do that.
01:32If you are a monthly subscriber, or an annual subscriber to lynda.com, you
01:36don't have access to the Exercise Files, but you can follow along from scratch
01:41with your own assets.
01:42Now let's get started with Perl 5 Essential Training.
Collapse this transcript
Prerequisites
00:00Before we begin learning about Perl, let's talk a little bit
00:03about prerequisites.
00:05Before you start this course, you should have a basic understanding of programming.
00:09This course is about Perl and Perl is a programming language, so you'll need to
00:13know the basics of programming before you get started.
00:16This is not a programming primer.
00:18It's not about how to write programs.
00:20It's about how to use the language Perl for writing programs.
00:25You don't need to be an expert, but you should have a little bit of experience
00:29at least writing working code in a modern programming language, and a modern
00:34programming language would be something like, C, Java, JavaScript, PHP, Python, any of
00:40those, anything that's a procedural language, or block-oriented language, or an
00:44object-oriented language will be fine for the prerequisite experience.
00:49You will need a computer system with Perl 5 installed.
00:53You're not going to find anything with Perl 4, or older versions of Perl, as a rule.
00:59Perl 5 is already about 15 years old as of the time of this recording.
01:04So, any system that has Perl on it has probably got Perl 5 on it.
01:09Most computer systems today, with the exception of Windows systems, come with Perl
01:14already installed. Macs already have Perl installed.
01:18Virtually all UNIX systems already have Perl installed.
01:21And if you have a Windows system, it's easy to install Perl, and we'll go over
01:26how to do that in an upcoming lesson.
01:29It's recommended that you have the latest version of Perl, which is Perl 5.10, as
01:35of the time of this recording.
01:37It's not necessary.
01:38Perl 5.6 or later will work just fine for most of what we cover in the course.
01:43We will have a chapter on New Features in Perl 5.10, but they're not required
01:48for the rest of the course.
01:51Finally, you will need a Text Editor; any Text Editor will do.
01:55A good programming Text Editor is strongly recommended.
02:00You do not want to use Word Processor, and you do not want to use the little
02:04Text Editor that comes with your operating system. You probably want to get
02:08a good Text Editor.
02:11In this course, we'll be using an integrated development environment called Eclipse.
02:16Eclipse is not required to do the course, although if you want to install
02:21Eclipse, there will be a lesson on how to install and configure Eclipse for use with Perl.
02:27Any Text Editor, whatever you normally use for your programming work, is going to
02:31work just great for working with Perl.
Collapse this transcript
What is Perl?
00:00What is Perl?
00:02Perl is a programming language, and that means simply that it's a language for
00:07defining computer programs.
00:10Perl is an interpreted language, which means that there is a runtime system that
00:16requires that the source code be present at the time that it's run.
00:19Of course, there are other ways to run Perl. You can use something like mod_perl,
00:23so if you see there is a limitation, there are ways to get around this. But in
00:28its native form, Perl is an interpreted language, and the source code must be
00:31present at the time that you run the script or program.
00:37Perl was designed for text processing.
00:40Perl originally came from the UNIX world, and it was designed to replace a
00:45number of other utilities that are commonly used in UNIX systems for system
00:49administration and scripting and building small applications and as such,
00:54it's good at processing text because virtually all of the configuration files in a
01:01UNIX system, the way that you do things in a UNIX system is by manipulating text
01:06and moving text around.
01:08That made it well suited for Internet work because the Internet grew out of the
01:12same culture. And a great deal of what goes on in the Internet is dealing with
01:17plain text files, and Perl is exceptionally good at that.
01:20And for that reason, you see a lot of Perl scripts on the Internet.
01:24You see a lot of web applications built in Perl.
01:27That sort of work is often done in Perl.
01:32Perl is a general-purpose, high-level language, and what that means is that you
01:37can generally do a lot of things with Perl.
01:40You can build all kinds of different applications and as a high-level language,
01:45that means that it's relatively easier to use than a lower-level language,
01:50something like C or Assembly Language or something like that.
01:54But Perl is a little bit easier to get into, a little bit easier to use, a little
01:58bit easier for a novice to read.
02:01Perl has a very simple and very flexible syntax.
02:06This means that there is often more than one way to do it.
02:09In fact, "there is more than one way to do it," is one of the slogans in the
02:13Perl world, and it's often pronounced TMTOWTDI.
02:16If you look at the letters that abbreviate those words and if you cross your
02:22eyes just so, you can see the words tim-toady in it.
02:26Perl is sometimes also called the Swiss Army Chainsaw of programming languages
02:30because it is so very, very flexible and so very, very powerful that you can
02:35do a great deal of things that you might have not even thought of doing with
02:39something like Perl, and you can do them easily and quickly with very little coding.
02:45Finally, perl, with a lowercase p, is the interpreter of the runtime environment
02:50for the Perl language.
02:52So, we're going to take a moment here and take a look at the Perl program itself.
02:59So, here I have a command line on a Macintosh, which is basically a UNIX system
03:03with a really slick front end.
03:05If you are running on a PC or on some other system, just do whatever it is that
03:10you normally do to bring up the command line, and these commands will work exactly the same.
03:16Type the word perl with -v, and that's a lower case v. Now what this does is it
03:22runs the Perl program, and it gives me the version number.
03:26So, this is the Perl that comes with Mac OS X version 10.6, and this is Perl
03:34version 5.10.0, which is almost the latest version as the time that we are
03:39recording this, 5.10.1 is out now.
03:42But if I could upgrade if I want, but it's really not necessary.
03:46The program perl, all lowercase letters, is the Perl Interpreter itself, and if
03:52I use a capital V, we get a whole lot more information about how it's compiled
03:58and what libraries are included and what options are -
04:01it's like a very, very detailed version string.
04:04And if I change directories into my Exercise Files here, I can actually run a script.
04:14I have hello.pl, and I can type perl and hello.pl, and it will run the program.
04:23So, that, in a nutshell, is what perl is in a lowercase p. It's the runtime
04:27environment or the interpreter for the Perl language.
Collapse this transcript
Installing ActiveState's ActivePerl on Windows
00:00If you're using a PC, running some form of Windows, then you probably do not
00:06have Perl installed.
00:07You can check really easily by bringing up a command line, like that, and you
00:15can type perl -v, and if you get Perl is not recognized, or something like that,
00:21then you do not have Perl installed, and you'll need to install Perl.
00:25So, we're going to go ahead and download and install the ActiveState Perl. It is free.
00:33And it's the recommended Perl.
00:35There is another popular Perl called Strawberry Perl, and it's just not quite
00:40ready for primetime as the ActiveState one.
00:43You're welcome to use it.
00:44All our exercises will work. You can learn the Perl language, but you'll be a little
00:48bit on your own as to how to get it installed and working and how to set up your
00:53development cycle with it.
00:54So, we're going to go ahead and download Perl from the ActiveState web site, so
01:00this is at www.activestate.com.
01:03So, we'll just click on ActivePerl and click on Download Now, and we'll go ahead
01:09and Download, Save the file, click on the maybe later for that, and we'll close
01:17this, and there we've got the download complete.
01:19Right-click on this and Open Containing Folder because that's nice and
01:24convenient, and we'll just double-click here.
01:27And we get this nice little dialog box.
01:29Depending on the version of Windows that you're running, you may or may not get
01:33exactly the same dialogs that I'm getting.
01:35You'll need to Run this.
01:37Let's say Next, and accept the License Terms, and we'll just go ahead on and
01:44install everything, and Next again, and Install.
01:51So, this is installing ActivePerl version 5.10.1.
01:57The way they are version numbering, this Build number means that this is the
02:00seventh release of Perl 5.10. All right.
02:09So, that's done.
02:10I'm going to uncheck the release notes because I don't need that.
02:12You can leave it checked if you want and take a look at them.
02:15Click on Finish, and we'll close this, and close this, and now when we run
02:23command, type perl -v,
02:27we get the Perl version.
02:29We can see this is Perl version 5.10.1, and that's exactly what we want.
02:36One more thing I'm going to do is I'm going to make convenient little
02:38shortcut over here.
02:40And what I like to do is I make a cmd.exe shortcut and in the Properties, under
02:48the Start in, I'll put the path to the Exercise Files, c:\users\Bill
02:55Weinman\Desktop\Exercise Files.
03:02Click Apply and OK.
03:05And now when I double-click on this, I get right to my Exercise Files directory
03:10there, and you can see that that's where all the Exercise Files are.
03:13I've got them on my Desktop.
03:14So, you can make this go wherever it is that you want it to go.
03:17So, I'm going to go into my Quick Start directory, which is right here, 01.
03:24And if I just press Tab, it completes it for me.
03:28That's a Windows 7 feature.
03:30Some of the earlier versions of Windows might not do that.
03:33And I want to run the hello perl, just to check it out, so I'm going to type
03:38perl and hello.pl, and there it says Hello, World!
03:44Take a look at that.
03:46That's just a very simple little Perl program, so perl and hello.pl.
03:52And so, we can see that Perl is working on this machine, and we have installed
03:56successfully ActiveState Perl version 5.10 on a Windows machine.
Collapse this transcript
Installing Eclipse on Windows
00:00So, now we're going to install Eclipse on this PC.
00:04This PC already has Perl installed on it. And Eclipse is an Integrated
00:09Development Environment, usually just called an IDE.
00:14Eclipse was originally developed for Java, and it's actually written in Java,
00:18and it's very popular and common.
00:22We're going to be using Eclipse with the Eclipse Perl Integration, the EPIC plug-in.
00:28And we're going to be using it as an Integrated Development Environment for Perl.
00:32Now, it's important to note, at this point, that this is not required to do this course.
00:37You can do all the exercises in this course.
00:39You can learn Perl from this course without installing Eclipse.
00:43So, if you have a preferred development environment on the PC, or some other way
00:49that you like to do this, by all means, go ahead and use that. You do not need
00:54to use Eclipse to complete this course.
00:57We're just using Eclipse, because it's convenient. And it provides us with a
01:01common development environment across all platforms, so that people that do
01:05choose to use it, will have exactly the same screen layout and everything, or at
01:09least the opportunity to have what I have here on the screen.
01:13So, you don't need to install Eclipse.
01:14But if you would like to, then follow along, by all means, and we will go ahead and do that.
01:19Now, Eclipse runs in Java, so it requires Java, and Windows PCs do not come
01:25with Java installed.
01:27I'm here at the Java.com homepage.
01:30I'm going to click on Do I have Java to find out if this PC has Java on it.
01:36In fact, this PC does not have Java, so I'm going to go ahead and download Java
01:41now, which I can do with this link here.
01:43I'm going to click on Free Java Download, Save File, and there we have it.
01:53Java has downloaded.
01:55It's not a very big file.
01:56I'm going to right-click on this and click on Open Containing Folder, because
02:01that's a convenient thing to do here with Firefox, and double-click on this
02:06installer, click Run, and Install, and there we go.
02:16So, now it is installing Java. There we go!
02:21We have successfully installed Java.
02:23So, I'll press Close, and I will close this window and close this window.
02:30You'll see here in the browser, it says, "Congratulations!
02:32You have installed Java."
02:34So, I will close that.
02:37On to Eclipse. Now, I'm going to go ahead and download Eclipse.
02:42Eclipse is the IDE, and it's written in Java.
02:44I'm going to click on this Download Eclipse button here.
02:49Now, there are a number of different choices for installing Eclipse, as you can see here.
02:56Feel free to look through them.
02:57Any of them will work for our purposes.
03:00I'm going to install the Classic Eclipse down at the bottom.
03:04You'll notice that there are many choices for how to download it.
03:08Here, if I just hover over this link with the mouse point, you see at the bottom
03:12in the Status bar, it shows an Eclipse for Win32.
03:16If I come over here, I can see that I get it that exact same link there or a
03:2264-bit version over here.
03:23I'm going to go ahead and install the default one.
03:26I recommend that you do too.
03:27The default one, which will be the main title of whichever one of these you
03:31choose, I'm choosing the Eclipse Classic.
03:34I'm going to click on that, and I'm going to download it from the default mirror here.
03:39It may take a minute. Go ahead and say Save. All right!
03:45Again, I'm going to right-click on this in the Download window and Open
03:49Containing Folder, and there we have Eclipse.
03:52Now, you'll notice that Eclipse comes in a ZIP file.
03:55Depending on your Windows version, different things will happen if you just
03:58double-click on a ZIP file.
03:59So, I'll just right-click on it, and I get this pop-up menu.
04:03I'll select Extract All.
04:08The default location will be right there in my Downloads folder.
04:10So, I'm going to click Extract.
04:13Depending on your computer, this can take a minute.
04:16There's actually quite a few files in here.
04:18It tends to slow down towards the end, and there we go.
04:23Windows has opened this folder up for me and your version may not do that.
04:27If necessary, you can just double-click on the folder, not the ZIP icon, but the
04:32folder icon, and get to the same place.
04:35So, I have it there.
04:35So, I'm going to use this other window, cleverly, to navigate to my Program Files.
04:42This is Windows 7, so I have a choice of Program Files or Program Files (x86).
04:47I'm going to select the Program Files (x86), and I'm just going to go ahead and
04:53drag this Eclipse folder from inside the Eclipse-SDK, where it unzipped.
04:59I'm going to drag that Eclipse folder right here into Program Files (x86).
05:04We'll just go ahead and move it.
05:06It doesn't need to copy, and we don't need to have a copy of that anymore, and
05:10close this other window, and open this up, and fire up Eclipse. Double-click on
05:17that, and I'll get this, "Are you sure?"
05:20Of course, I'm sure.
05:22Now, it wants me to select a workspace, so you can just use the default or what
05:28I do is I have a place where I put such things. So, I go into Files, and I click
05:34Make New Folder, and I call it Eclipse, and select OK.
05:40Now I have Files\Eclipse.
05:42That's where I like to put things.
05:44It's really up to you.
05:45As long as you know where it is and you know how to find it.
05:48So, I'll click OK, and Eclipse fires up.
05:52Now at this point, it's a good idea to check for updates.
05:57Now since we just downloaded from their web site, we can presume, probably,
06:01safely, that there aren't any updates available.
06:04I've had it happen where installing Eclipse, I've downloaded from the web site
06:08and I've checked for updates and there have been updates available.
06:10It's a good idea to just go ahead and check, and this can take a few minutes.
06:16Okay, so there we are. There is nothing to update this time.
06:21Now we're going to install EPIC.
06:23Now if we go back over here to the browser, click on the EPIC tab, and this
06:27is an epic-ide.org.
06:31Go ahead and click on Download.
06:33You'll see this whole description.
06:35It actually makes a lot of sense to install EPIC from inside of Eclipse.
06:41In this case, I've got two different versions that I can do the testing version.
06:44In this case, most of the time, I stay away from testing versions.
06:48In this case, it's been so long, and it is considered so stable in the community
06:53that I'm going to go ahead and use the testing version, and it does say, recommended.
06:58So, I'm going to highlight this and just copy that URL, because I know that
07:03we're going to need it.
07:04Then come back over here to Eclipse, and I'm going to click on Help >
07:10Install New Software.
07:13Then right in here, I'm going to paste that URL and select Add.
07:18I'm going to name it EPIC, E-P-I-C, and click OK.
07:26You'll notice at this point, oh,
07:27it came up quickly that time.
07:29Sometimes, it may stay on that pending for a long time.
07:33Just be patient. You will eventually get to this screen.
07:37I'm going to click the check box and say Next.
07:42It's found EPIC Version 0.6.35. Click Next again. Accept the terms of the
07:49license, and Finish.
07:52Now we'll install EPIC.
07:54Again, this can take a while.
07:57You'll notice a few things happening. You'll notice, sometimes up here, we'll
08:01get this dialog box, and I'll just say OK, because I know that unsigned content is okay.
08:07Sometimes, you'll see the word Blocked come up in that other dialog box, and
08:11sometimes it will stay there for a while, and you just want to go ahead and
08:15let it do its thing. It is working.
08:17Some of the messages look like it might not be working.
08:20Just let it go through until you get to this point, where it is strongly
08:23recommended, and this is not just plain recommended.
08:26This is strongly recommended that you restart Eclipse.
08:29So, I don't even know why they let me not restart it.
08:31I'm just going to go ahead and restart it.
08:33And that will restart Eclipse, and we'll have the Perl integration in there.
08:40It remembered my workspace.
08:42So, you can use this as a default if you want to.
08:45I'm going to leave that unchecked for now, and I'm going to say OK. And here we go!
08:51We're now in Eclipse.
08:52So, a lot of different choices here. You can learn about Eclipse if you like.
08:56I'm going to go right to the workbench, and I'm going to go right over here and
09:01change my Perspective to Perl Perspective.
09:04So, I click on this little doodad there and click on Other and click on Perl.
09:11So, now I know that I have Perl installed in my Eclipse.
09:17I'm going to maximize the window. Create a new Perl project.
09:22I'm going to name it Perl 5 Essential Training. Click Finish.
09:31And now within that, I'm going to right-click and say New > Folder.
09:38I'm going to click on Advanced, Link to a folder in the file system, and browse for it.
09:46On my Desktop, I have my Exercise Files.
09:49Now this is where I put the Exercise Files. You can have them wherever you like.
09:53But that's what I'm selecting is the Exercise Files from this course, and I'm
09:57going to say OK, Finish.
10:00There we have the Exercise Files.
10:02So, I'll click on this little arrow next to it and it opens up, click on the
10:06little arrow next to chapter one, and I just want to run the hello.pl, and make
10:12sure I'm double-clicking on it. There it is.
10:13There is our Hello World in Perl.
10:15Then in the Run menu, I'm going to click Run, and there we have, in our Console
10:22at the bottom, Hello, World!
10:24So, we can see, at this point, that Eclipse is installed, Perl is installed, the
10:30Perl extensions to Eclipse are installed, and we have everything we need for it to be working.
10:36So, I know we've been sitting here for awhile, but I'm going to take a moment
10:40here, and we're going to do a little bit of configuration.
10:44In the Window menu, under Preferences, there's a couple of things that we want to do here.
10:50I want to go under Perl EPIC, and Editor.
10:54Now, the way that this comes, by default, it's going to insert tabs.
11:00If you like tabs, go ahead and leave the tabs alone. My files don't have tabs in them.
11:05I'm not a fan of tabs, because they don't work across platforms and
11:09across environments.
11:10So, I'm going to click on Use spaces instead of tabs, and 4 spaces per indent.
11:15This will make everything work just the way that we expect it, and I'm going to say OK.
11:19There are a lot of other things that you can do to configure here, and I'll
11:24leave that up to you.
11:25But there you have it. The Eclipse IDE is installed. Perl is working, and it's
11:30all tested and working on this Windows PC.
Collapse this transcript
Installing Eclipse on Mac
00:00So, now we're going to install Eclipse on a Macintosh.
00:05Now it is important to note that you do not need Eclipse in order to
00:09complete this course.
00:10Eclipse is not required.
00:12Eclipse is an integrated development environment, or an IDE.
00:15As such, it's a useful thing, but a lot of developers work in different ways and
00:21so if your preferred method of coding is to use a stand-alone text editor or
00:28different IDE, VI or whatever, then do it that way.
00:33Eclipse is not required for this course.
00:36This is a course about Perl and as such, whatever editor or development
00:41environment you choose to use will work, and you will be able to follow along
00:45with the exercises just fine.
00:47All of that said, let's go ahead and install Eclipse on this Macintosh right now.
00:53So, we're here at the Eclipse web site, which is www.Eclipse.org, and I'm going
00:58to click on the big yellow button that says Download Eclipse. And that will
01:02get me this page here where there are a number of choices for different Eclipse downloads.
01:08Feel free to look through these and if you decide that one of them works best for you,
01:12go ahead and install that one. Any of them will work of them work for our purposes.
01:16We're going to install a Perl plug-in, which is not on this page, so I'm going
01:20to start with the basic Eclipse Classic, which is this last choice down here.
01:25Then I'm going to install the EPIC Perl plug-in on top of that.
01:28So, I'm going to go ahead and click on that - get this download started here.
01:35Eclipse is written in Java. It requires Java.
01:39It runs under the Java environment, and the Macintosh, of course, comes with
01:44Java already installed, and if you have been running your updates, then your Java
01:48should be up-to-date.
01:49You might want to make sure before you install Eclipse that you have an updated
01:54Java environment on your Mac. Here we go.
01:57The download is complete.
01:59So, I'm going to right-click on this.
02:01If you have a one-button mouse, you can Ctrl+Click on it.
02:05Select Show in Finder, and there it is in my Downloads folder.
02:10I'm going to double-click on this now. Eclipse does not have an installer per se.
02:14So when I double-click on this, it's going to -
02:16first, it will uncompress, then it will unpack the .tar file, and it gives me this folder.
02:22And in the folder, all of the parts of the Eclipse package, and I'm just going
02:26to take that entire folder and drag it into applications and let go. So, that
02:30moves the folder out of the Downloads folder and into the Applications folder.
02:35And I'll select that and scroll down and find Eclipse in here.
02:39Here is the Eclipse application.
02:41I'm going to drag that into my dock because I'll be using that, and then I will close this folder.
02:46I can close the downloads and run Eclipse.
02:51And now it's going to ask me where I want to put my workspace.
02:54Now you can use the default location if you like.
02:57I like to put it some place else.
03:00I keep a Files folder for things like this.
03:03I'll just go ahead and create a new folder inside of there and call it
03:08Eclipse, and that will be my location, and I'll say OK.
03:19Now Eclipse starts up and you get this lovely screen here with all kinds of choices.
03:24Now before we select any of these choices, I know, from personal experience, that
03:29sometimes I can download something from somewhere, and this has happened with
03:32Eclipse before, and I didn't get the latest version.
03:35So, I'm going to go in the Help menu and select Check for Updates.
03:40But what it does is make sure that I'm running the latest version of Eclipse.
03:47Okay, so this means that we do have the latest version and if not, it would give
03:51us an opportunity to install that.
03:54Now we are going to go ahead and install the Perl plug-in for Eclipse, which is called EPIC.
03:58I go back to my browser here.
04:01When I click on the EPIC web site tab that I have already opened and what this
04:05is is an EPIC plug-in for the Eclipse IDE. and I click on Download, and you want
04:12to install EPIC from inside of Eclipse.
04:15And this is the URL to use.
04:18Now the reason that this is recommended is because this is actually the stable
04:22version. The older version is still available.
04:25The newer version, it considers it a testing release, but it's been so long
04:29since there has been any updates, and the word that I've been reading is that
04:34this is completely stable and ready for prime-time, or as ready as anything is in
04:39terms of a Perl IDE, and I've been using this.
04:43This is the version that I'm going to recommend that you install.
04:46Select this URL and right-click and select Copy. Switching back to Eclipse, I'm going
04:54to go to the Help menu and Install New Software. And then right up where it says
05:00Type or Select a site, I'm going to paste in that URL and click Add. And I'll go
05:06ahead and name it EPIC and you see the word Pending comes up here. And that can
05:12happen for a long time or very quick, like it did in this case.
05:15Select the EPIC main components and select Next.
05:20I'll select Next again. You see that it's found the EPIC Version 0.6.35 and
05:27press Next. Accept the Terms of the License Agreement. Select Finish, and now
05:33we'll start installing.
05:35Now as it installs, you'll see different messages come up here.
05:40Some of them say something about that something is blocked.
05:43Don't worry about it.
05:44It's running several processes at once, and it's just waiting for one to finish
05:49before the next one starts up.
05:51This can take a while. It can go quickly.
05:53It depends on how busy the web site is. Go ahead and say OK when you get this
05:59warning about the Unsigned Content.
06:04It is now strongly recommended, and this is not just plain recommended. This is
06:07strongly recommended that you go ahead and restart Eclipse, and so I'm going to
06:12say yes and restart Eclipse, because there's just no reason not to.
06:17And it gives me my default location again, and there we have it. Eclipse is running.
06:25So, now you can browse through these different choices if you like.
06:29I'm going to go directly to the workbench, and I'm going to maximize the window,
06:35and I'm going to switch to a Perl view.
06:37So, over here, you have your open perspectives in a JAVA perspective, and I'm
06:43going to switch to a Perl perspective.
06:44So, I click on that open perspectives and I select other and Perl, OK.
06:51And now I'm going to open a new Perl Project.
06:55I will call it the Perl 5 Essential Training, say Finish and so now I have a Perl project.
07:05And I'm going inside of this.
07:07I'm going to right-click on that, and I'm going to say New > Folder.
07:14Click on Advanced and Link to a folder in the system and Browse and go right to
07:20my desktop and my Exercise Files and select that and Finish.
07:26And so now I have the Exercise Files loaded in here, and they're not copied.
07:30This is linked to the file system ,so that's important.
07:34So, just to make sure everything's working, I'm going to go in here and select my
07:37Hello, Perl, Run from the menu, and there is our output Hello, World!
07:43So, we know that this is all working.
07:45One more thing really quickly before we're done:
07:48I have a thing about tabs and so I'm going to in the Eclipse menu where the
07:55Preferences and under Perl EPIC, open that up, and I'm going to click on Editor.
08:01I'm going to say Use spaces instead of tabs.
08:03You don't have to do this.
08:04This is my way, but the files that are in here are done this way and so
08:09this'll make them match.
08:11And 4 spaces per indent, say OK, and now we have installed the Eclipse IDE with
08:19the Perl plug-in, and we're ready to go ahead and write some Perl.
Collapse this transcript
1. Perl Quick-Start Guide for Experienced Programmers
Hello World
00:00So, let's start by taking a look at Hello World in Perl.
00:05Hello World is a tradition in programming, and its purpose is to get all of the
00:11coding out of the way, so we can look at the environment.
00:14It's really about, how do I do my development cycle? How do I write code,
00:20edit code, test code, debug code, go around in that cycle? And it's not about the code itself.
00:28This is not about, how do I write the world's simplest program in Perl?
00:32This is about, how do I do these other things around of the coding using a
00:37piece of code that's simple enough, that it can get out of the way, so I can
00:40look at my environment?
00:42In this case, I am using the Eclipse environment.
00:45You may be using a different environment.
00:47So, our purpose here is to take a moment and get familiar with whatever our
00:52development cycle is going to be.
00:54In this case, here in Eclipse, I am going to go ahead and open my Exercise
00:58Files, and you can do that yourself.
01:01Again, if you're not using Eclipse, just use whatever tools you are used to.
01:05Open a folder and open a file, so in the 01 Quick Start folder, inside Exercise
01:10Files, you'll find hello.pl.
01:13And I'll just double-click on that here and bring that up, and there is the code.
01:17So, I can see it in the Editor. I can edit it.
01:21I can do whatever I need to do there, but the first thing I want to do is I want to run it.
01:25For my part, I am just going to select Run from the Run menu, and there it is.
01:30It's running this Console down here, and it says, Hello, World!
01:34For your part, if you are doing it a different way, you may be running it on a
01:38command line, and that would look different.
01:40For example, here I have a command line, and I'm going to change directories
01:47into my Exercise Files, which is under Desktop and Exercise Files and 01
01:53Quick Start. And I am going to look in this directory, and I see there is all
02:00my different scripts.
02:01If I want to run Hello World, I just I type perl hello.pl, and that's how you
02:08would run a Perl script.
02:09There are other ways to do it.
02:11Again, whatever environment you are using, you need to do a little experimenting
02:16and find the way to run a Perl script in your environment.
02:20I just want to take a moment and talk about the two different Hello World
02:26scripts that I have here.
02:28One of them is called hello-simple, and you'll notice that that one doesn't have
02:33any of this extra information.
02:35It doesn't have the comment at the top.
02:36It doesn't have the use strict and use warnings.
02:39I consider all of these things important, and we will get to them in different
02:43parts of this course.
02:45This is technically the simplest script that you can write in Perl.
02:49And we can run it here using Run and there the hello-simple.
02:53It says Hello, World!
02:56down there in our Console.
02:58And again, in the command line environment, we can do the same things, say perl
03:02hello-simple.pl, and it will run that as well.
03:09So, that's our Hello World script, and we have the two versions of it there.
03:14And that should give you an opportunity to see how to do the edit and running a
03:19development cycle in your environment.
Collapse this transcript
Counting lines in a file
00:00Continuing in our Quick Start, if you already have some programming experience,
00:05you're just looking for quick answers to how to do simple things in Perl, you
00:09are in the right place.
00:11In this lesson, we are going to look at how to read a file in Perl.
00:15So, in your 01 Quick Start folder, in your Exercise Files, you will see countlines.pl.
00:22Open that up.
00:23I am going to maximize this window, so we can look at the code.
00:26This is a simple script that simply reads the file, counts the lines in the file.
00:31And so you can see, it starts by declaring a variable and the name of the
00:38file, linesfile.txt,
00:40opens the file, and it reads all of the lines in the file into a variable,
00:46using this syntax here.
00:48And then it closes the file, and it counts the number of lines in the file
00:52and prints that result.
00:54All of these details will be covered in other parts of this course.
00:58If you are looking for Quick Start on just how to read lines in a file and
01:03count them, this is the place.
01:05I can go ahead and run this, and there it is.
01:09There are 50 lines in linesfile.txt.
01:12And if we look at linesfile.txt right here, we can see it's got 50 lines of
01:19that, and there they are.
01:27So, just quickly, this is the simple way to open a file.
01:31We are going to do a whole chapter on File I/O later on, where we will be
01:35using a module for reading files, which is more flexible and a more
01:39object-oriented way to do it.
01:41But you simply use the open function, and the first argument is a file handle,
01:47which looks like that in Perl.
01:49And the second argument is the file name, and you can see that the file name is
01:55a variable that's declared up here, and it's linesfile.txt.
01:59And then, using that file handle with the angle brackets, we will read the
02:03entire file all at once and assign it to an array.
02:08So, this is an array, and it will have one line per element in the array, and
02:14then you can close file because it's already red, and it's in the lines array.
02:19So, the lines array here, you can count the elements in array by simply
02:24casting it to a scalar.
02:26And again, we'll look at that in the chapter on arrays and how to do that,
02:32and assign that to a variable, and then you can print out.
02:35There are count lines in file name and you get this result.
02:40So, that's the simple answer to "How do I read a file and count its lines
02:45in Perl?"
Collapse this transcript
Using a loop in Perl
00:00Continuing in our Perl QuickStart, if you're looking for a quick answer to, "How
00:06do I use a loop in Perl?" you are in the right place.
00:10In this case, we are going to take our countlines example from the reading a
00:14file movie, and we are going to do the same exercise but using a loop instead.
00:20In the countlines script, if you remember, I'll go ahead, and I'll open that here,
00:24we read the entire file into an array all at once.
00:28The problem with this approach is that if your file is very, very large, you run
00:33the risk of crashing your computer, having a stack overflow, having problems
00:38with that, because you've ran it all, all at once.
00:40In this movie, what we are going to do is we are going to read that same file.
00:45We are going to read it line by line, using a loop instead.
00:49So, here we have the same file name, linesfile.txt, which is just a simple
00:56little flat file with 50 lines of text in it.
00:59In this case, we are going to open the file and read the file line by line, and
01:05we are going to use the IO::File module.
01:09In the countlines example, we just use Perl's built-in native, open, close and
01:15reading the file handle technique.
01:17That's fine for some very simple applications, but most of the time, you are
01:22going to want to use a richer interface.
01:25In this case, we are using the IO::File interface, which is very, very common in Perl.
01:30This is the way that file IO is commonly done.
01:34It's an object-oriented interface.
01:36So, the first thing we do is we create a new file handle object, and that's
01:41using this syntax here.
01:43So, IO::File and this dash and right- angle bracket to create an arrow and new
01:51So, new is a method inside the IO::File object -oriented module, and new has two arguments.
01:57It's got the file name and an R, which indicates that we are opening the file
02:02for read-only and not for writing.
02:05If we didn't get a file handle, if it didn't work, we can print an error
02:09message, which will say, "Cannot open file name," and we'll take a look at that in a moment.
02:14Then once we have the file opened, we count the lines.
02:19So, we start with a count = 0 and we use a while loop, and we'll talk later
02:25on about the different kinds of loops available in Perl, and we'll get into
02:28the details on that.
02:30So, we get a line, one at a time, and we count them one by one using the
02:35increment operator for our number, which started at 0. And so for each line, it
02:40will get incremented by 1. We are all done.
02:43We close the file handle and we print out the results.
02:48So, if I go ahead and run, you'll see there's our results.
02:52There are 50 lines in the text file.
02:54If for some reason it cannot open the file - and let's just go ahead and change
02:58the name of the file here.
03:00So, I am going to put an X in front of that.
03:01The file name will be wrong, and it won't be able to open the file.
03:05So, I'll save and run.
03:10Now, we get this error message, Cannot open xlinefiles.txt (No such file or directory).
03:18So, what this is here's the error message, Cannot open, and there is the file
03:22name from the variable here $filename, $filename.
03:26The error message is in this special variable, and we'll have a whole chapter on
03:31the special variables.
03:32This is the one that gives you errors from the operating system $!
03:37or as we say, dollar bang.
03:40That gives you the error message from the operating systems.
03:42So, Cannot open $filename error message.
03:46In our results, we saw that it says Cannot open linesfile.txt (No such file or directory).
03:55So, we'll change this back, and we'll save, and we will run again, and there we have it.
04:03There are 50 lines in lines file.
04:06So, that's how you use a loop. Move this back.
04:10So, that's a very simple loop, using a while loop.
04:13We have got a Conditional here, also,
04:15a little bonus. You can see how to do that.
04:17You see how to get an error message out.
04:20This is a much more robust way to do the count lines.
04:23It's not going to crash
04:24if you have got a lot of lines in your file; it's reading them one by one.
04:29This is a much more robust way to read a text file in Perl using a loop.
Collapse this transcript
Using subroutines in Perl
00:00Continuing in our QuickStart, we are going to look at subroutines now. If you
00:04are looking for how to do subroutines in Perl,
00:07for simplicity, for modularity and readability, this is how you do
00:12subroutines in Perl.
00:13Our third countlines example, again, we are counting the lines in a file.
00:17And this time, it's a more complete program, and we've broken up the
00:21functionality into several different subroutines.
00:24Personally, I like to use a main subroutine for a main entry point, and
00:30oftentimes, I'll just do it like this.
00:32At the top of the File, I've got my use strict, warnings, IO:File, and then I
00:39just call the main function and using this syntax here, that actually calls the
00:44main function with the command line arguments as function arguments.
00:49So, if you are familiar with C, this does something similar to how that works or
00:53Java or any command line-oriented language.
00:56This makes it work, kind of like you would expect.
00:59So, here we have our main subroutine, and the first argument is the $filename.
01:06So, if you were to call the command line and say the countlines3 and the file
01:11name, then it would bring that in.
01:13And if you didn't call it, you can use this logical OR, and it will assign,
01:18instead, linesfile.txt.
01:22Then the $count we get from our countlines function.
01:25So, that's all encapsulated.
01:27It's all hidden in that countlines function and makes it very simple from the
01:31main subroutine point of view.
01:33Then you simply report the results.
01:36So, this little three line main, it tells you, at a glance, exactly what's going on.
01:41Then you can look at the countlines function.
01:44I have a little comment at the top that says, "Here's how you call it and
01:47here's what it returns."
01:48I think that's a great habit to get into as you write subroutines.
01:53Then here is the body of it.
01:55This is where all the work is done.
01:57We read in the file name.
01:59We give an error if we don't have a file name. We open the file.
02:03We give an error if we cannot open the file.
02:05Here is a nice way to do that.
02:07This is simpler than how we did it in the last example using the logical OR.
02:12This is a very low precedence OR that Perl has that makes it very easy to do things this
02:18You go and you create the instance of the object, in this case, open the file.
02:22And if that didn't work, you just give an error message.
02:25It's a very nice simple syntax for that.
02:28Now, we count the lines with a while loop.
02:32Again, this is exactly the same as we did in the last example, except we are
02:36using the postfix while, which is something that is fairly unique to Perl.
02:42There aren't a lot of languages that have a syntax like this.
02:45So, it allows you to do this entire loop on one line and you just say count
02:50while you are getting lines.
02:51It's very easy to read and easy to look at and easy to code.
02:55Then we return the results.
02:57We have a couple of other little subroutines here, which are just useful
03:00things that I like to do.
03:02I have one called message, which just prints a string with a new line.
03:07In Perl 5.10, there is a new keyword called Say, which does the same thing.
03:13But unfortunately, Perl 5.10 is not widely enough deployed to be able to
03:18really use those new features in production and expect them to work on
03:21anybody else's computer.
03:23So, this way that I have been doing this for years using my little
03:26message subroutine and
03:28a similar one for error where I print the $0 is the file name of the Perl script
03:35and then $e and for the error message, which we get from the shift here.
03:41Simply print an error (string) and then exit and so when have an error it does -
03:45it prints the error message and exits.
03:47So, that makes all of these other things very easy.
03:50So, we can use our error function here.
03:52We can use the error function here, and we can use the message function here,
03:59just to print out our status message that there are so many lines in the file.
04:04So, it makes the whole program very readable, and it puts the functionality of
04:10the different things that we're doing in their own nice, little
04:12self-contained, little containers, like this one here for counting the lines.
04:17So, yes, the script is longer than our other versions.
04:20In my opinion, it's far superior.
04:22It's got better error reporting and better modularity.
04:26It's going to be a whole lot easier for you to work with something like this using
04:30this kind of a modular structured programming style.
04:34So, let's go ahead and run it, and we'll run it right here.
04:37We see there are 50 lines in the text file.
04:41If we go and change the file name, like we've tried before -
04:45I'll save that and run again -
04:47we see that we get an error message.
04:49In this case, we're using the error subroutine.
04:53So, let's go ahead and go back to the other view where we can see all of this at once.
04:58In the error subroutine, we see that we have this $0 here, and that's what
05:04prints out all of this, and that's our entire path name to the program we are running.
05:08So, we can see this error is coming from countlines3.pl.
05:12The error says Cannot open the file because there is (no such file or directory).
05:16So, we'll ahead, and we'll put our file name back and save and run again and we
05:24get the 50 lines in the text file.
05:29So, that is the more modular structured, more modern programming technique
05:33version using subroutines.
05:36Now, you have the basics of Perl.
05:39You have the basics.
05:41If you're an experienced programmer, and you're just looking for the
05:44basics, you've got that.
05:46In the rest of the course, we'll be going through the details of how all
05:50these different things work and all the different features of the Perl
05:53programming language.
Collapse this transcript
Using Perl's documentation
00:00I want to take a quick moment, and I want to talk about Perl's online
00:03built-in documentation.
00:06On any system that has Perl properly installed, you can type Perldoc at a
00:11command line and get complete documentation on any subject within Perl.
00:16So, for example, if I want to know about the IO file modul,e I just type perldoc
00:20IO::File, like that, and I have the IO file documentation.
00:27The format of the documentation is very similar to man pages if you're familiar
00:32with UNIX man pages.
00:34This is pretty much what they look like, and they are built using Perl's
00:38internal pod documentation, P-O-D, which stands for Plain Old Documentation, and
00:44we'll be talking about that later in this course.
00:47So, basically, if you want to know anything about anything in Perl, you just
00:52type that perldoc with that subject and you get all kinds of - you get
00:56whatever documentation is available, and then in the case of the modules, it's
01:00the documentation that was written by the module authors, and it's in this
01:03perldoc man-like format.
01:06If you want to get documentation on a built-in function, you say Perl doc -f and
01:12something like print, which is a built- in function, and you get everything that
01:16you ever wanted to know about print. And I am using the Page Up and Page Down
01:20keys. That may be different on your system.
01:23If you're using the Eclipse IDE, you can have access to all the perldocs just by
01:30highlighting something, and in this case, I'm using the right mouse button and I
01:36see Perldoc right here and I click on that, and then it comes up.
01:41I can maximize this window.
01:42Again, you've probably got a bigger screen than I do, and you can arrange these
01:46windows differently, and there is all the documentation on that module.
01:50In fact, you can also get the source code for the module, and in this case, you
01:54can see the pod documentation there at the top, and then there's the actual code
01:58down further down. And likewise,
02:01if you want to get documentation on a built-in function, you just highlight
02:06that built-in function.
02:07Let's see, we've got print down here some place, and it's Perldoc, and there
02:13you get the documentation on that built-in function.
02:16So, this is Perl's built-in documentation, and any properly installed Perl will
02:21have this available.
Collapse this transcript
2. General Syntax
Understanding how Perl uses whitespace
00:00As we begin our discussion of general syntax of the Perl language, we are
00:05going to start by talking about whitespace. And in your 02 Syntax Folder, in
00:12your Exercise Files,
00:13I just want to take this file here, this syntax.pl, and make a copy of it.
00:18And so I'm going to right-click on it and select Copy, and right-click on the
00:24Folder and push Paste.
00:26I want to call it whitespace.pl.
00:29And so now I'm working with a copy of this.
00:33I'll close this one, and I'll open whitespace.pl, and in that way, our
00:39Syntax File remains untouched while we play around with the copy, which is
00:44always a good idea.
00:46In order to discuss whitespace, we want to turn on the Features in the Editor
00:49that allows us to see whitespace and manipulate whitespace.
00:53And so I'm going to go into my Preferences here in Eclipse, and you'll do this
00:57with whatever Editor that you are using, assuming that it has features like this,
01:01and most of them do.
01:02And I'm going to take out the Insert tabs for spaces.
01:05I'm going to turn on the Show whitespace characters.
01:08This is under General > Appearance > Editors > Text Editors.
01:12I am going to press Apply, and then I know, in Eclipse, I need to do
01:16the same thing in the Perl > Editor.
01:19Down here, I need to take out that.
01:21Otherwise, it'll continue to Insert Spaces instead of Tabs. Then we'll press apply and OK.
01:27And now we can see the whitespace characters.
01:30We have the little paragraph marker, which is for the new line.
01:34We have these little dots for spaces and if inset a tab here, you'll see that I
01:39get this double right angle bracket thing instead of a tab.
01:44So, now we can talk about whitespace.
01:47whitespace in Perl is new lines, space characters and tabs.
01:54And whitespace is pretty much ignored in most circumstances.
01:58There is a couple places where whitespace is actually required, and so we'll talk about that.
02:03Let's start the discussion by just removing a bunch of whitespace from this
02:07function here, and I'm going to actually just shorten this text down a little
02:11bit, and we'll get rid of this whitespace, and so now we have this subroutine here
02:18that's got only whitespaces between the words sub and main, and that's actually required.
02:24There has to be some kind of whitespace in order for that keyword to be
02:28isolated, and so that the Interpreter knows that's a key word and not part of
02:32the name of the function of the subroutine.
02:36And so I'll go ahead, and I'll Save and Run this, and we can see that we get the
02:41word short text there. So, this is actually still working, even though I've taken
02:46out all of that whitespace.
02:47So, most of the whitespace is ignored.
02:50I can put in some whitespace here.
02:52I can use maybe a Tab there.
02:55I can put whitespace here and here.
02:57I can put whitespace there, and there, and there, and all of this whitespace,
03:02and it can be new lines,
03:03it can be combinations of things. I can - it's a new line and a tab there.
03:10I could actually indent this a bunch, if I wanted to.
03:12I can do all of these things, and this will still run.
03:16I'll Save, File > Save and Run, and it's still working.
03:23So, all of that whitespace is actually ignored, and in fact, even this
03:26required whitespace, I can put in a new line and a couple of tabs, and that will still run.
03:33That's pretty much how Perl uses whitespace.
03:37In most places, you can eliminate it entirely.
03:39It's really just necessary where it's necessary to separate keywords and end
03:44things that need to be separate.
03:47And other than that, whitespace can be wherever you want it to be for
03:50formatting purposes, using my Undo function here to bring this back to
03:57something like its original state.
03:59And this is the style that I happen to like.
04:03I think it's important, when you're program,
04:05to use the whitespace - if you've got a language where whitespace is optional -
04:10to use the whitespace as a way of setting apart the things that are
04:14important, making it easy on the eye, so that you can read the code when you
04:20come back to it at later time.
04:21So, I tend to use whitespace as a way of formatting the code so that I can read
04:28it later, and that, in my opinion, is the function of whitespace in a language
04:32like Perl, where whitespace is mostly ignored.
Collapse this transcript
Terminating statements with semicolons
00:00Continuing with our discussion of general syntax in the Perl language, we're
00:04going to talk now about semicolons.
00:07I'd like to start by making a copy of the syntax.pl file, so that we're not
00:12working with the original.
00:13Let me go ahead and do that here and call it semicolons.pl, and we'll go
00:21ahead and open that up.
00:23You'll notice that statements in Perl are terminated by semicolons.
00:28There is one at the end of that statement there.
00:30There is one at the end of that statement there, and there is one there.
00:34In general, they are required.
00:37There are some exceptions where a semicolon is not required.
00:41A semicolon is not required at the end of a block.
00:45So, if we take this semicolon, here, out - because it's at the end of a block,
00:49it's followed by this closing curly brace - it doesn't actually generate an error at all.
00:54I can go ahead and save this, and run, and you'll see the script still works
00:59fine, and it doesn't generate any errors.
01:01I'm going to go ahead and put that back.
01:05On the other hand, if I insert another statement and go ahead and save that,
01:13you'll notice that we have errors.
01:14You'll see that the Eclipse system has already started to parse it, and it has
01:18found this error here.
01:19It's a syntax error, "Bareword found where operator expected."
01:24Now this line here is where the error actually is.
01:27But this is the message from Perl.
01:30This is the Editor knows that that's what the problem is.
01:34If we go ahead and turn on Explain Errors/ Warnings here, we can see that we have two errors.
01:41We have the syntax error, and we have this Bareword found where operator expected.
01:47Now the syntax error is in red, and that's matching up with this.
01:50The Bareword found where operator expected is matching up with this.
01:55So, what's actually going on here, the Eclipse system is obscuring
02:00what's actually going on.
02:01It's trying to make it a little bit more friendly for you.
02:03I want to show it to you in the command line, so that you get an idea of the
02:07kind of errors that you are actually going to see when you have a problem like
02:11this, so that you'll recognize it, and you'll be able to say, "Oh!
02:14I must be missing a semicolon."
02:15I'm going to switch to my terminal here, and I'm going to run this script.
02:23Here is the error message that you get out of Perl.
02:27You'll notice that both of these errors are saying line 13.
02:32And if we look at line 13, that is this line here. It is not the line where we
02:38actually have the problem.
02:40The reason for this is that the Perl interpreter doesn't really notice
02:44that something is missing until it gets another statement, and it says, "Wait a minute.
02:48This is not what's expected here."
02:51It's treating this all as one statement, but it sees two function calls without
02:55any punctuation in between them.
02:58So, it's not really discovering the error until line 13.
03:02That's why you have this "Bareword found where operator expected at line 13."
03:07That's the first thing that it noticed.
03:09I'm not expecting that.
03:11In this context, it's not even knowing that that's a function call.
03:15So, the problem is, and here it says, syntax error at line 13, and that's as good
03:22as the interpreter can do.
03:25So, when you get that error, when you get the error that says, "Bareword
03:28found where operator expected," or even just a syntax error, you want to look
03:32at the line before and say, "Am I missing a semicolon or a comma or some sort of punctuation?"
03:39So, I'm going to go ahead and put the semicolon back in there, and we're going to save it.
03:44Now we see all of our error messages go away.
03:47This, of course, it stays.
03:49It's just the explanations, but our error indicators here go away.
03:53We can run the script, and it works just fine.
03:56We get the two messages.
03:59If I go back into the command line and I run the script, we see the result that we expect.
04:06So semicolons, in summary, semicolons are required in Perl.
04:11They terminate a statement.
04:13So, a statement must have a semicolon at the end of it.
04:16The one exception is, at the end of a block, a semicolon is not
04:21necessarily required.
04:22But it's still a really, really good idea.
04:24I suggest that you put them there.
04:26If you're missing a semicolon at the end of a block, Perl is not going to complain.
04:30But if you go and insert, say another statement or two after that and forget to
04:35put in the semicolon, you're going to get errors, and you're going to have to
04:37figure out where those errors are.
04:39It's best just to put them in anyway.
04:42They're supposed to be there.
04:43It's just an exception to the rule.
04:45So, semicolons terminate statements and you want to use them all the time, even
04:51when they're not absolutely required.
Collapse this transcript
Creating comments
00:00Continuing our discussion of general syntax in Perl, I'm going to talk about comments.
00:06So, we'll start by taking this syntax.pl script and making a copy of it.
00:12I'll name it, comments.pl, just so we don't overwrite the original.
00:17Go ahead and edit it and do whatever we want to it.
00:21I'm going to start by writing a little subroutine so we have something to
00:25write a comment about.
00:27This is a recursive factorial.
00:30It's typically a programming exercise that you might get in school if you're
00:35learning programming.
00:38A factorial is a mathematical function.
00:41It's the product of all the integers up to and including the integer that
00:45you are factorialing.
00:47So, we'll start with the number and shift or return 0;.
00:53That means that the function will be passed a number and if it's not passed a
00:59number, I'll just return zero, which will be the answer for a missing number.
01:04If $n > 1 - because if it's not, then the factorial is always 1 - then we'll
01:12return $n * factorial
01:16as the recursive part, because it's calling itself, $n - 1.
01:22And else, return 1;.
01:26So, in the case where it is equal to 1, we just return 1.
01:29Now I can explain all of this in comments if I want to.
01:34I can say here, factorial (n), returns the product of all integers up to and
01:47including n. I can say here, return 0 if no n.
01:57So, comments in Perl are introduced with the hash mark, that symbol there,
02:02little tic-tac-toe-y-looking thing.
02:05Everything including the hash mark and to the end of the line is ignored by
02:11the Perl interpreter.
02:12So, they can be in a line by themselves like that, or they can be out here at the
02:17end of a line that actually has code in it.
02:21So, anytime you have this hash mark, everything from there to the end of will
02:25be ignored by the interpreter.
02:26So, that is a comment.
02:29So, I can say here, only compute for n > 1, return 1 for n = 1.
02:46I can say recursion, because it's calling itself.
02:50So, I have all these comments that I can make.
02:53In real life, I don't tend to write this many comments.
02:56Comments are an excellent thing.
02:58They're great thing to do, because it explains what's going on to somebody who
03:04comes by to read it later.
03:06If you have too many comments, there is a tendency for people to just read the
03:10comments, and then they miss the code.
03:12So, something like this one that says recursion is really superfluous.
03:17This one here is probably also superfluous because you can see from the code, if
03:21($n >1), so there's some guidelines for how to comment.
03:28Then up here, I can just call the function.
03:31I can say $n = shift or 5 if nothing is passed in and $r = factorial of n, and
03:47message ("$n factorial is $r").
03:54I can save this and run it. 5 factorial is 120.
04:01If you remember, the first few factorials from math class many, many years ago,
04:07you'll remember that that is the correct answer.
04:09You'll notice that I forgot the semicolon at the end here, and it worked anyway,
04:14because it's the end of a block.
04:17I'm going to go ahead and put that in.
04:20So, here we have, just an example of where you might use comments and how they
04:26are formatted in Perl.
04:28So, it's a good idea to comment your subroutines, like this -
04:31I usually do - with how it's called and what it returns.
04:36You might want to have comments on anything that you might want to explain that
04:39might actually warrant some explanation.
04:42I don't know. In this case,
04:43in real life, I might not have commented any of this, because this all seems
04:47pretty simple to me.
04:48But for the benefit of people who might come after me and might want to read
04:53this code later, I might put these comments here, and I might say something up
04:57here, like, computed recursively to make that obvious.
05:03But that's how comments are used in Perl, and that's how comments are formatted in Perl.
05:08Those are some general guidelines for using comments in your code.
Collapse this transcript
Best practices for formatting code
00:00Continuing our discussion of general syntax in Perl, I would like to talk about
00:04a few best practices in making your Perl scripts.
00:08So, we'll start with our syntax.pl, and we'll make a copy of it, and we'll
00:14name it general.pl.
00:18Go ahead and open that.
00:19But I'm going to maximize this, because we're really just going to be
00:22talking about this.
00:23This is a template, and I've included it in your Exercise Files.
00:28If we look over here at the Exercise Files, outside of all these folders, you'll
00:33see one that says template.pl.
00:35And that's what this is.
00:39This has in it just a lot of the things that I tend to put in my Perl scripts
00:44as a starting place.
00:46I use something very similar to this.
00:47When I'm writing a new Perl script, I'll start from a little template file.
00:50It will have pretty much the same stuff that's in here.
00:54So, let's talk about what these all elements are.
00:56The first one you'll see is at the top, and this is called the shebang line
01:00in the Perl world.
01:02And that refers to these two characters here, which is the comment marker,
01:07the has mark, or the pound sign, followed by an exclamation point, which is often
01:11called a bang.
01:13What that does is it tells the UNIX shell to go ahead and run this interpreter
01:20when it encounters this kind of a file.
01:22So, the interpreter here is /usr/bin/ perl, which is the common location of Perl
01:27on a UNIX-based system.
01:28So, I'm on a Macintosh here, which is a UNIX-based system.
01:32If I go over to my command line, which is a bash shell - this is a UNIX shell -
01:37I'll look at the files here, and I see there is my general.pl, which is the file
01:43we're looking at in the Editor there.
01:45If I run it the normal way, just say Perl and general.pl like that, you'll see
01:50that it executes the Perl script.
01:52I can also just say ./general.pl, and it will run the same way.
02:01It is actually running Perl.
02:02It's doing exactly the same thing.
02:04It's just that the shell is reading that first line, and it sees that first line
02:12refers to a Perl program, and it will go ahead, and it will run Perl.
02:16It just does the same thing.
02:19It's a shortcut;
02:20it's a convenience, and it's a good idea.
02:22There are some environments like a web server environment, which may also read
02:27this line and find the right interpreter for doing something like running CGI.
02:31So, it's a good idea.
02:32And again, if you have it in your template, it doesn't cost you anything to
02:35put it there.
02:36The next couple of lines are just comments that say who wrote the script, how
02:41you can contact him, and who it belongs to.
02:45It's always a good idea to have that there.
02:46You can also add a line that says this is generally what the script does. You can
02:50have a little bit of usage information.
02:52You can refer to another file that has documentation.
02:55So, a lot of good things you can do in a comment block at the top of
02:58your script.
02:59So, I suggest you always include one.
03:02The next two lines are use strict and use warnings and most Perl programmers,
03:07most Perl books will tell you, always use strict and use warnings, and I'm going
03:11to say the same thing.
03:12It will give you a few extra error messages while you're writing and debugging.
03:17In the long run, it will clean up your coding, and it will make your programs
03:20more portable and just more reliable.
03:23So, it's a great idea to always include use strict and use warnings.
03:29This next bit is something that a lot of programmers don't do.
03:32I do.
03:33I find this to be an important discipline in programming.
03:38Perl does not require a main function.
03:40Some languages do, like C and Java.
03:42I think it's a great discipline.
03:46It keeps that main piece of code tidy.
03:48It keeps it all in one place.
03:50It keeps from having code outside of the scope of a block in the global
03:55scope, where it can messy.
03:57It can get lost.
03:58It can be more difficult to maintain.
04:00It can get interspersed with all kinds of declarations and things that belong
04:04out there.
04:05So, I just think this is a great discipline.
04:07It's not required, but again, it doesn't really cost anything.
04:11You just put it in your template, and it's always there.
04:15Likewise, with these two and sometimes I'll include some other ones as well
04:19in my templates.
04:21Message, again, starting in Perl 5.10, there is an equivalent function called
04:26Say, but at this point in time, as I record this, I can't really count on 5.10
04:32being installed on many systems.
04:34So, I'll go ahead I'll continue to use this for a few more years until 5.10
04:39is widely deployed.
04:40In the meantime, all this is is it's this function here.
04:44It allows me to write something to the standard out and not have to put a new
04:49line at the end of it, which is oftentimes easy to forget.
04:52It's just a convenience function.
04:54Likewise, with error, I'll often have this go to standard error instead
04:57of standard out.
04:58In this case, it's going to standard out.
05:00We'll talk about that when we talk about I/O and streams, but what this does is
05:05it outputs an error message, and it exits.
05:09That's a great convenience for error conditions and debugging.
05:13So, there you have it.
05:14These are, I just think some minimal best practices, some minimal habits that
05:18you'll want to get into.
05:20Like I said before, it's easy.
05:21It doesn't cost anything.
05:22You just put it in your template and use it as a starting place whenever you
05:25start a new Perl project.
Collapse this transcript
3. Variables and Values
Understanding values and variables
00:00I'm going to talk for a moment about the concepts of values and variables, and
00:03how these are represented in Perl.
00:06Values represent data, whereas variables contain values.
00:13For example, here we have a Perl statement, $number = 42;.
00:19The dollar sign indicates that this is going to be a variable, and there's several
00:25different symbols that can introduce a variable.
00:27We'll get to those later on.
00:29In this case, the dollar sign means that the variable is one-dimensional, which, in Perl,
00:33is called a scalar.
00:35And number is the name of the variable.
00:38So, you have the dollar sign followed by the name of the variable.
00:40The equals sign is the assignment operator, so we're assigning a value to the variable.
00:47The value is 42, which is an integer number, and the semicolon, of course,
00:52terminates the statement.
00:54So, here we have a Perl statement that assigns the value, 42, to the
00:59variable $number.
01:02Perl provides several types of values.
01:06Values can be numbers, as it is in this case.
01:09They can be strings, which are a sequence of characters that may be displayed
01:14on a screen.
01:16These numbers and strings can be aggregated into different type of structures,
01:20including scalars, which is a one- dimensional value that can contain one
01:25value, Arrays, which can contain sequences of values, Hashes, which are like
01:31arrays, but they are keyed or indexed, and References, which are values that
01:38point to other values.
01:39We'll get into all of these later on in this chapter.
01:43It's important to note, at this point, that Perl uses context to determine type.
01:48Perl is not a strongly typed language.
01:51In other words, when you declare a variable, you don't declare its type.
01:55Its type is determined by the context of the value that's being assigned to it.
02:01We will get into that in a lot more detail in this chapter as well.
02:05So, the concept you want to get from this is the distinction between value
02:09and variable.
02:10A value is the data itself, and the variable is the container that contains
02:16the value.
Collapse this transcript
Declaring numeric variables
00:00In your Exercise Files folder, you'll notice a folder 03 Variables, and inside
00:05of that folder, there is a file variables.pl. Go ahead and make a copy of that
00:10now, so we don't write over the original.
00:12We'll just call it numbers.pl.
00:15Now, go ahead and open that, and there we have numbers.pl.
00:24We're just going to start right here and start declaring some variables,
00:30my $decimal = 12345;.
00:35So, what this does is it declares a variable called decimal, and because of the
00:39dollar($) sign, this is a scalar variable, which means it's a one-dimensional
00:43variable and assigns the value 12345 to it, which is a decimal number.
00:48Now first of all, notice this my keyword, and what that does is it declares a
00:54variable to have a lexical scope inside the block and which you have defined.
00:59If you hover the mouse over here in Eclipse, you will get a little pop-up
01:04definition and we see this definition: "A 'my' declares the listed variables to
01:11be local (lexically) to the enclosing block, file, or 'veal'."
01:16So, why this is important is because with strict and warnings invoked up here, if
01:23you do not declare the lexical scope of a variable, if you just say decimal
01:28equals like that, you will get an error. And you see if I hover my mouse over
01:31here, it says global symbol requires explicit package name.
01:36So, all that means is you forgot to type my.
01:39You want to put my there, and that makes this lexically scoped to inside
01:45this block.
01:46What that means is that if you have another variable on the outside here, = 23456,
01:57and you go ahead and use this,
02:00you'll be using the one that's inside the scope and not the one outside of
02:03the scope.
02:04So, if I say message($decimal) and run that, we will get the 12345.
02:14If I had not declared this in here, and we run that, we would get the 23456.
02:23That is the meaning of the my declaration.
02:29It declares the variable as being lexically scoped inside of the block that
02:36you're enclosing it in, and you just need to do that all the time.
02:39You need to always have the my there as long as you're using strict
02:42and warnings.
02:43It's there as a discipline to make your code more reliable, so that you don't
02:48end up mixing up your name spaces and having a variable that you think is one
02:53thing and turns out to be something else entirely.
02:56So, this is a decimal number, because we have assigned a decimal value to it.
03:01A decimal value is a sequence of numbers that does not begin with 0.
03:05If it begins with zero, it's an octal number.
03:12So, that would give us an entirely different value.
03:15I am going to go ahead here, and I'm going to put in these message statements as
03:19I go along, decimal is $decimal and octal
03:27is $octal, and I see I have a typo here.
03:33I misspelled decimal there.
03:39Now, if we save this and run it, I'll see that decimal is this number and octal
03:45is this entirely different number.
03:47That's because of this leading 0 here tells us that this is an octal number and
03:53so it assigns it in base 8, but when we print it here, this will always print in
03:59decimal base 10 and so it's converting it, and there is the value that we get.
04:04So, we are getting a different value.
04:05So, just know that if you have a leading 0, you are always going to get an octal
04:09value and not a decimal value.
04:12We can also do hexadecimal, which is base 16, and that looks like this, and
04:18I will go ahead and copy and paste here, say hex is $hex and if I run that,
04:31it looks like that.
04:33Again, it's printing it in decimals, so we get this other looking value.
04:38We'll go ahead and show you some more types of numbers.
04:42We can do binary.
04:46That's done with a 0b, and go ahead and do a print statement for that, binary,
05:00and run it and see that we get yet another value.
05:05And the other types include a floating-point number, or a number with an
05:18exponent, scientific notation. e56 means that you would move the decimal point
05:28over 56 places to the left.
05:31We'll go ahead, and we'll print those as well. float, $float and exp for the
05:47scientific notation one.
05:49I will go ahead and save and run, and we see these values here.
05:55These are the different types of numbers available, and you'll notice that the
06:00assignment statement has the various types of numbers on the right, but on the
06:04left, they all look pretty much the same because we are just assigning them to
06:08a scalar container.
06:11The value itself, the context of it is what's determining the type.
06:16So, the way that I type this is what determines the type of the number.
06:21So, those are the basic number types that are available in Perl, and that is how
06:27you specify them in an assignment.
Collapse this transcript
Declaring character string variables
00:00Continuing our discussion of variables in Perl, we're going to talk
00:03about strings.
00:05So, we'll go ahead and make a copy of this variables.pl,
00:08so we don't write over it and just call it strings.pl. And we'll open that
00:16and here we go.
00:18So, this, of course, is a string because it's in quotes, and if we were to assign
00:26it to a variable instead, and we could say my $s = "this is a string";
00:38and if we message($s);
00:43and Run that, it will say this is a string.
00:48So, strings can be in single quotes or double quotes.
00:52This editor, of course, wants to match quotes automatically, so I have to do a
00:56little finagling there.
00:58This will work just as well, since this is a string. And the difference is is
01:06that if I had another variable, say my $ n = 42 and I put a $n in there like that,
01:18and run it, if I have the single quotes, it doesn't interpolate.
01:22It'll go ahead and say $n. If instead, I have it in the double quotes - I'm just
01:28going to go ahead and do a different one
01:31where $s = "this is a string:
01:34$n", like that. What does this warning say? Ah, masks an earlier one.
01:42So, that error means that I have named two variables with the same name in this
01:47scope, so I'll call this one s2 and this one s1, and I'll message($s1), and I
01:53will message($s2), and I'll save that and run it.
02:01Now we'll see that the second time it actually interpolates.
02:05It takes this $n, and it replaces it with the value, so it's reading that
02:11variable and interpolating the variable, rather than just displaying the
02:15characters $n. With the single quotes, it does not interpolate, and so it will
02:20not get you the value of $n. It will just put out the characters, a dollar sign
02:25and an n character.
02:27So, that's the difference there.
02:29Now, in fact, you don't always have to use quotes.
02:33If I wanted to say put this $n in quotes, I would have to say \" and \" in order
02:42to actually get the quote character, and I've got two quote characters next to
02:47each other because one of them is escaped with the backslash and one of them is
02:50not, and then I'll get quote marks around this. Save and run.
02:57I get quote marks there.
02:58If I want quote marks in this one, because it has the single quote, I can just
03:02put in a quote mark like that, and I don't have to escape it because there isn't
03:07a danger of it being interpreted as ending the string. And so I'll Save and Run
03:14and I get the quote marks there.
03:16The opposite is true if I want to use the single quotes. If I want to use the
03:19single quote here, I just put it in there like that because I'm in double quotes
03:25and so I don't have to escape it. But in this case, if I want to use the single
03:29quote, I actually have to escape it and use the backslash single quote because
03:34my string is enclosed in single quotes and so I'll Save that and Run, and you'll
03:42see that now we have single quotes.
03:45You can get around this by using Perl's special quote operator, which is a q
03:50followed by a delimiter.
03:52So, for example, here in this first one, I can do a single quote by saying q
03:57and using any of the delimiter characters.
04:00So, in this case, I'm going to use say a curly brace and I'll go ahead and put
04:05the other curly brace at the end here.
04:07Now I don't have to quote these single quotes.
04:10I can just do it like that and because there's just one q, this works exactly
04:16like the single quotes.
04:17So, it won't interpolate the $n, and I'll Run that, and it looks just like that.
04:22And in this other case, if I wanted to interpolate I can use two qs, and I'll
04:28put in the bracket, and Eclipse goes and matches my bracket for me and so I
04:34have to move it over there. And now I have two qs followed by a delimiter and so
04:39this will interpolate.
04:40It works just like a double quote.
04:42So, I'll go ahead Save and Run, and we have that there.
04:47So, I can put double quotes in here without escaping them, just like this,
04:53and that will work.
04:55I'm going to Save and Run, and we have our double quotes there, and
04:59it's interpolated.
05:00It's getting me the value.
05:02You can use any delimiters. For example,
05:05I could use a vertical line instead of the curly brace, and in that case, I don't
05:11need a matching one because there's only one kind of them. And this will work
05:15just fine there. And so this is a flexible way of being able to declare strings
05:22without using quote marks for cases where you might want to actually have
05:25the quote marks inside of the string.
05:29Finally, let's talk a little bit about concatenating strings.
05:33If I wanted to print both string one and string two, I could say message($s1 .
05:40$s2 );, and it will concatenate them.
05:45It will put one right after the other and so there won't be a space.
05:49So, after this quote, there will be just the word 'this' without a space there.
05:54So, I'll Save and Run, and I have a third line here.
05:59This is a string:
06:01'$n'this is a string, and it's got the two strings concatenated with the
06:04concatenation operator.
06:06So, if I wanted actually to have a space there, I would have to put one in. So, I
06:11have a quote and a space and another concatenate operator with a dot there, and
06:17that will put a space in between them.
06:20So, I could run that and, of course, you can concatenate literal strings.
06:25This s1 could become something like Eclipse is trying to figure out what I
06:30mean instead what I say, this is a string, and I'll say dot this is another
06:41string. And, of course, in between them, there's not going to be a space, so
06:45let's just go ahead and put one in, and we'll maybe use a colon character. And
06:51you'll notice that in this case, I've used the single quotes instead, and I'll
06:55go ahead and Save and Run.
07:00Now the first string has this.
07:01This is a string colon. This is another string, and there it gets all
07:06concatenated down here.
07:08So, that's how strings work in Perl.
07:11Strings are scalar values.
07:13They are one-dimensional, and they can be concatenated using the dot operator.
07:18Single quotes do not interpolate variables; double quotes do. And you can, of
07:24course, use a single q or a double q with any delimiter to get around having to
07:30escape your quote marks.
07:32So, that's how strings work in Perl.
Collapse this transcript
Declaring lists and arrays
00:00We're going to talk about lists and arrays now. And in your 03
00:03Variables directory,
00:05we are going to make a copy of the variables.pl file, and we'll call it
00:12lists.pl, and we'll go ahead and open that, and we'll talk about lists
00:19and arrays.
00:20A list is simply a list of values or variables or list of things.
00:26And so we can say my @array = - now an at sign, like a dollar sign, specifies a scalar
00:36variable and an at sign specifies an array or a list variable. Then in parentheses, I
00:43can put a number of different values (1, 2, 3, 4) like that, and now I
00:49have an array that has four scalar values in it, and those values are numbers.
00:56And they're 1, 2, 3 and 4.
00:59A simple way to look at the values of an array is to use the join function.
01:05It's a built in function. And so I can say message join, and I'll put a colon
01:11for the separator and @array. And what this will
01:16do is it will display these values with in a colon in between them, so I'll go
01:21ahead, and I'll save, and I'll run and we have 1, 2, 3, 4, with colons
01:28in between them.
01:29These values in the list can be anything.
01:32I could put a string in here, put the word two, and I can Save that and Run it,
01:41and you'll see we now have the word "two" in the middle layer.
01:44And in fact, if I want to, I could assign this to a list of scalars instead
01:52of to an array.
01:53I can say my $one, $two, $three, $four
02:01and so those are four scalars that are named one, two, three and four,
02:06and I can say = ( 1,2, 3, 4 ) like that, and then I can
02:12just print them out like normal variables, one, and I'll just go
02:20ahead and copy and paste that four times and name them two, three and four. And
02:29so now I'm printing out those four variables one at a time but you see I've
02:32assigned them all at once because I've simply assigned one list to another, like
02:39that. And so we'll Save and Run, and we'll see that it prints them 1, 2, 3, 4, on the
02:47line like that, just as they are here 1, 2, 3, 4.
02:50I'm going to go ahead and get that out of the way and delete these.
02:58We have here our array, and the array has four values in it.
03:05If I want to just look at one of them, I can say $array with a subscript,
03:11and inside of that subscript I put a number. If I say subscript 1,
03:15I will get the second element. I'll get the one here that says
03:20two because these subscripts are zero- based, so 0 would be the first one and
03:25one is this one and two is that one, and three is that one. And so $array
03:30subscripted to 1, like that, will give me the second one, which says two, and so
03:37there we have two.
03:39So, there's a couple of things to notice about this.
03:41One, of course, is the subscript is in square brackets, like that, and that we do
03:48not use the at sign when we're subscripting an array.
03:51And the reason for this is that what we are extracting from the array here is one
03:57scalar value, so the scalar indicator is the dollar sign and so even though the array
04:04variable is an array variable, and it was declared with the at sign,
04:09the dollar sign is used when we want to subscript and get one value out of it, using
04:15the subscript operator, the square brackets.
04:19So, in this case, we've gotten the second value.
04:21We could, of course, get the first value with a 0. And we'll run that and we
04:27see we get the number 1 there, or let's say we wanted to know how many elements
04:33there are in the array.
04:35I can say there, I get a little flummoxed by the way that Eclipse interprets my
04:41quote marks there, and it did it again, so I need to delete first and then okay,
04:48there are, and I can say . scalar @array. array, like that, elements in the array
04:59and what this does - you'll notice the string
05:03concatenation operator
05:04there and there and so there are space - and then this will give us the number of
05:12elements in the array, the count of them, which in this case is four, because
05:15there's one, two, three, four elements in the array.
05:18So, what scalar does, it's like a cast - if you know what casts are in other
05:22languages - what it does is it gives this array a scalar context.
05:28And in a scalar context, what this @array syntax returns is not the list of
05:34elements in the array, but the number of elements in the array. And this is just
05:39a little Perl-ism, and so in the scalar context, what you get from an array like
05:45this is the number of elements. And so this will say there are four elements in
05:50the array when we run it. And so we'll go ahead and save and run and we get there
05:55are four elements in the array.
05:58So, that's how you declare an array.
06:00That's how you subscript an array, and that's how you use an array and how
06:04you would assign a list of values to an array. And if you're interested in how
06:08you slice out combinations of values out of an array, I'm going to talk about
06:13that in the next movie.
Collapse this transcript
Pulling slices from arrays
00:00So, now we are going to talk about a technique called slices, and this is a very
00:04useful, very cool technique that Perl has.
00:08A lot of modern languages have slices, or something like them.
00:11It's not something you'll use everyday, probably not anyway, but when you do
00:15need them, you'll be really happy that they're available.
00:18So, let's go ahead and make a copy of the variables.pl, and we'll call
00:22this slices.pl.
00:26And we'll go ahead and open that up. And I am going to start out by declaring an array.
00:32And we will give it all the numbers from 1 to 10, using this -
00:40you haven't seen this before -
00:42this is the range operator. And what that does is it gives us a list of numbers, 1
00:47through 10, just as if we have typed 1, 2, 3, 4 all the way up to 10. Instead,
00:53it's done with this nice little range operator 1..10, like that.
00:57So, if we take a look at the array at this point, we use the join operator, like
01:02we did in the last movie, array and take a look at it,
01:08you'll see that just as if we have typed all those numbers, it comes out
01:121:2:3:4:5:6:7:8:9:10, just like that.
01:16And so, this will be useful for looking at our slices.
01:20Let's say that instead of all of the numbers, I just wanted to see, say the
01:26first and the forth and the seventh element of the array.
01:31So, I can just type in, 1,4,7 like that, separated by comas.
01:37What this will do is this will give us the elements numbered 1, 4, and 7, which
01:43is actually the second, fifth and eighth elements.
01:47So, we will get, 2, 5 and 8.
01:51Go ahead and Save that and Run, and there we have 2, 5 and 8.
01:57So, these are the elements numbered one, you'll remember that we start at zero.
02:02So, the element number one is actually got a 2 in it, and the element number
02:06four has actually got a 5 in it, and the element number seven has actually
02:09got eight in it.
02:10We can use the range operator here too, if we want to.
02:13We could say, 0..
02:142, 7 and so we will get a 1, 2, 3 and 8. Go ahead and Save that.
02:25And there we have 1, 2, 3 and 8.
02:27So, we use the range operator.
02:28So, this is actually - what this is is it's a list, and it's a list of the
02:33elements that we want.
02:34They don't even have to be in order.
02:35We can say 9, 3, 5, and that should be a comma, not a period, and go ahead and Save and Run.
02:46And you'll see that we get these out of order now 10:4:6.
02:50So, this is called slices, and as you can see, you can do a lot of neat
02:55things with them.
02:56Notice that I'm using the at sign here.
02:59When you've subscripted array before, to get one element you use the dollar sign.
03:04And that's because your result was a scalar, one, 1-dimensional value.
03:09Because our result now is a list, it is the slices of the array,
03:14we use the at sign because our result is now going to be a list and not a scalar.
03:21So, that is how you do slices.
03:23They can be very useful.
03:24You probably won't use them every day, but when you do use them, you'll be
03:28really glad that they are available.
Collapse this transcript
Understanding hashes and associative arrays
00:00Now we are going to talk about hashes, which are a special type of array.
00:04Sometimes they are called associative arrays.
00:08These are arrays that have keys and values, rather than just scalar elements.
00:13And so we'll start by making a copy of the variables.pl.
00:18We'll call it hashes.pl, like that.
00:23And open that up and start by declaring - move this out a little bit - start by
00:31declaring a hash variable.
00:35So, hash is with the percent sign, like that, and then it is very much like a list.
00:43And in fact, it is a list.
00:45It's a special case of a list.
00:47So, we'll say this and that, and you'll notice the Equal sign with the right
00:54angle bracket, and that declares that this is a key, and that is a value, and
01:01then I can say comma.
01:03Actually, instead of that, let's just make that something else like foo.
01:07And that can be bar, and the other can be baz, like that and a semicolon.
01:21And so we have now a hash array, or an associative array with three keys, and
01:29they are associated with three values.
01:31So, this is foo.
01:32That is bar and other is baz.
01:36We can look at any one of these elements using something like this, $hash and
01:45say, that, like that.
01:50And so this syntax here - again, we use the dollar sign because our result is
01:55a scalar.
01:56Hash is the name of our hash variable and in curly braces, we have the key that
02:03we are looking for, which is that.
02:07So, what we will get is the value bar.
02:09That's what will display down here.
02:11So, let me go ahead and Save and Run, and there we have bar because that is the
02:18value that is keyed on that.
02:20If I were to put other here and Save and Run, we get baz, which is the value that
02:30is associated with other.
02:33So, there you have the basic way that you declare and read the value of a
02:41keyed element in hash.
02:44Of course, there are some other things that we can learn about this.
02:47In fact, this is a special case of an array, and so these arrows and the equal sign
02:53with the right angle brackets were simply shortcuts for commas.
02:57And the reason that they are there is to enforce the even numbered element rule
03:02that in a hash you must have an even number of elements, but this syntax here
03:09will actually work exactly the same.
03:12I'll go ahead and Run that and you see we get the same value.
03:16It's much harder to read, and it's not anywhere near as easy to write, and so we
03:23will go ahead, and we'll use that great little hash key value shortcut with the
03:29equal sign and the right angle bracket.
03:33And so we can see that that's an important syntactic element, but like so many
03:37things in Perl, there is really more that one way to do it. And occasionally, you
03:41will see lists in arrays cast into hashes.
03:45And it's important for you to know that they are technically the same
03:49data structure.
03:50They're just used in different ways.
03:52So, I'll go ahead here, and I'll Save this, and we will go ahead and Run and
03:55make sure that we're back where we meant to be.
03:59There is some other things that you can do with hashes. You can get a list
04:03of all of the keys.
04:05A list of the keys would be with the keys functions, so we can say keys and
04:12%hash, and that will return a list of the keys.
04:16Now because it's a list, I can't just display it this.
04:19I have to use something like join with a colon, and we will go ahead and put in
04:25a comma there and make sure that we have the right number of closed parentheses.
04:29And I'll Save that and Run.
04:34So, there is a list of the keys, and you'll notice that they are out of order:
04:37other, that, this, actually in reverse order.
04:40But that's not a guaranteed order at all.
04:43If you want a guaranteed order, you need to sort it.
04:46So, you could say sort, and again, we will move that parenthesis out there, so we
04:53have the right number of them.
04:55And so this will put them in alphabetical order, Save and Run, and other and
05:02that and this, and so that is the alphabetical order.
05:05In fact, you can get the values as well, let's say values instead of keys, and
05:10you'll get foo, bar and baz.
05:12And those would be in the order bar, baz and foo probably because they are
05:17alphabetical. Go ahead and Run that, bar:baz:foo.
05:23So, those are the important elements of how hashes work.
05:27It's very common to read a hash in some sort of a loop.
05:31And I am just going to give you an example of that. You use a foreach loop. And
05:34we will talk more about these loops later.
05:36I will give you an example of how this works.
05:41So, this is a very common construct that you will see,
05:47something like this foreach my $k for the keys and get a list of the keys, and
05:54they will come out sorted.
05:55And then I can say something like $v = $hash {$k}, like that. For each one of
06:03these, that will give me the value, and then I can print something like this.
06:08I can say $k is $v, and we'll get a list that will say for each of these in
06:15sorted order of the keys and its associated values.
06:20We will Save and Run, and there we have other is baz.
06:24That is bar, and this is foo.
06:28So, this is commonly how you will see hashes used, in some sort of a loop like
06:32this that pulls out the keys and gets the values based on the keys.
06:37So, that is how associative arrays or hashes work in Perl.
06:42That's how you declare them using the list of key value pairs with the commas
06:48and these lovely equal and angle bracket syntax.
Collapse this transcript
Getting value pairs using the each function
00:00If you watched the movie on hashes, you'll remember that we stepped through the
00:03hash using the sort keys in a foreach loop.
00:08I want to talk about another way to do this, and this is a way that you
00:11probably won't use often, and we'll talk about why and why I didn't show in this
00:15way in the first place.
00:17We will start with the each-begin.pl file, out of the 03 Variables folder, in the
00:23Exercise Files folder.
00:24We will make a copy of that, and we will just call this each.pl.
00:31Open that, and we'll see that this kind of where we left off in hashes movie.
00:37We have a hash defined, and it has these elements in it.
00:40And we have this foreach loop that loops through using sort keys, loops through
00:46the hash and prints out the key and the value.
00:49So, we go ahead and Run it.
00:51We will see that this is our result.
00:54So, I want to show you another way to do this.
00:57And this other way uses a simpler- looking structure. We use a while loop,
01:09like this.
01:10And in this case, we no longer even need this line because we have
01:15already assigned it.
01:16The way that this works is it declares this list of variables, $k and $v, and it
01:23uses the each function to get each key and value pair from each element of
01:28the array.
01:29And it assigns those as a list and so this list pick out up in to these two
01:34elements, and then you can just print them out in one fell swoop, as it were.
01:38And while this might look a lot simpler on the surface, it has one
01:43key disadvantage.
01:44Let me go ahead and Save this and Run it, and you'll see we get exactly the same
01:49result, in this case.
01:51The problem is is that the order that these come out, the order that the
01:56elements are traversed out of the hash, is actually random.
02:01And in this case, it appears to be the same order.
02:04It is the same order.
02:05The problem is that we only have three elements in this hash.
02:08And if we do it in a longer hash, we will see that it's not in order.
02:13So, by way of comparison, I am going to go ahead and print a divider here.
02:20And then we will put the other loop back after this one the way it was before the foreach loop.
02:27We will assign the value like that and print out the message.
02:48And when we run this, we'll see that we have two lists that look exactly
02:52the same, in this case.
02:55There they are.
02:57If we start with a larger set of data, instead of this hash that we declaring
03:02ourselves, with just the three elements - we will go ahead and use one of the
03:05system variables and what this one is is this is the system environment, all of
03:10the environment variables.
03:11It's a rather long list.
03:14And it's something that you might to look at every once in a while.
03:16We will go ahead and Save this and Run it, and you will see that we have two
03:21copies of this list.
03:22The first copy of the list has all of this stuff in it.
03:27You'll see it's in no particular order.
03:28The second copy of the list is actually in alphabetical order, and that's
03:33because here we have sort keys.
03:35So, we are ordering it by the keys, and this is the problem with each.
03:40Because each returns each element as a list of key value as an array with two
03:47elements, there is no easy way to sort it.
03:50So, it's always going to come out in some random order, some guaranteed to be
03:55not in alphabetical order.
03:58Obviously, with a short list, it sometimes may end up being alphabetical,
04:02but it's not guaranteed to be in any particular order, whatsoever.
04:05And with foreach, for just a little bit more of work, not really very much more
04:10work, you can sort in whatever order that you want to.
04:14And so that's the advantage of sort keys instead of using each.
04:19That's why you'll see it done this way more often, when you need to traverse a
04:23hash and get the keys and values.
Collapse this transcript
Understanding the undef value
00:00In our discussion of variables and values in Perl, we need to talk about a special
00:05value called Undef or undefined.
00:09It's the undefined value, and it's represented by the word Undef.
00:13So, let's go ahead and make a Copy of our variables.pl and call it undef.pl and
00:19learn about the undef value.
00:21So, go ahead here and declare a variable. And we'll give it the undef value, and
00:31then we'll print it out.
00:34We need to put my in here, and message, x is $x. Now this is going to give us an
00:44error, and the reason for that is that we have included an undefined value in a
00:49string, and Perl doesn't like that.
00:51We'll go ahead and run it, and see the error;
00:54Use of uninitialized value $x in concatenation (.)
00:58or string at line 13, and that's right here, and you'll notice it tried to
01:04print it anyway.
01:06So, the reason for that is that $x is the special, undefined value.
01:11We simply made in an empty string like that.
01:14So, if we simply give it empty string and Save and Run, and we get no error, and we
01:23have x is, and it's still nothingness.
01:26So, there's a difference between an empty string and this special undef value.
01:31So, the undef value is the undefined value.
01:35If we take x and give it a value, like say value,
01:41and then go ahead and copy these lines, and take out the my for the second time,
01:49because it's already given a scope, and take this out, and make it undef,
01:56now we will get our error again.
01:58Our error will be for line 15 but not for line 13.
02:03Because what we've done here is we've taken $x, and we've made it undefined
02:07again. We've uninitialized it.
02:08So, go ahead and Run it, and there we have that error message, and this time,
02:13it's for line 15, which is right there. And the first time we Run this it says
02:18x is value.
02:19That's x string value.
02:20And the second time we run it, it is that undefined thing.
02:26Where else is this useful, besides for creating errors?
02:28I'm glad you asked.
02:30Let's go ahead and create a function, a subroutine, and we'll say, sub isnum,
02:37and so this is going to be a function that's going to tell us whether or not
02:41a value is numeric.
02:43And it's simple to do, $n=shift, and that will give us the argument.
02:49And we're going to test for the undefined value with the defined function, and
02:58in this case, were checking to see if the variable that's been passed to us
03:03through shift is defined.
03:05And we'll talk about subroutines and functions and how they work later on.
03:09But for now, I'll just explain as I go along.
03:12We're going to test if this number is numeric, using a regular expression.
03:21So, it's testing that it has any characters that are not a zero through nine
03:25character, and if it does, then we will return the undef value.
03:34We don't want to return zero or empty string, which would be considered false
03:38in Perl.
03:39We want to return this undefined value so that we can return the value, otherwise
03:45actually return the value of the number. And that number may be a zero, which
03:50would be understood by Perl as being false.
03:53And so we can't just test and say is it true or is it false?
04:01We have to use the defined function to test what is num return.
04:05So, we can say if(defined isnum $x,)) and we know that it is a number, and we can
04:15say, message("x is a number") and we'll even show the number.
04:23Else message x is most definitely not a number.
04:30And so we'll Save this, and Run it and we see, in this case, x is not a number
04:40because we have the word value in there.
04:41If I put a number in there, and Save that and Run it, then it says x is a
04:47number, and it gives us the number 42.
04:48If I put a zero in there, zero is considered false, and so here we actually
04:56get it.
04:57But if I had not used this defined function, if I just said, if, is numx like
05:02that, then it would say that it's not a number, and it actually is a number.
05:07And so that's why we use the undef value for not a number, instead of just
05:14returning a zero or false is a number.
05:19So, that's the usefulness of undef, and, of course, you can also use it to
05:25uninitialize variables that have previously been declared and defined and
05:30given a value.
05:31We saw that.
05:31And it's useful to know that when you get that error message of using
05:37uninitialized variable in a string or concatenation, that the undef value is
05:42what's going on there.
Collapse this transcript
4. Statements and Blocks
Assigning values to variables
00:00We're going to start our discussion of statements in Perl by looking at the
00:04assignment statement, and we'll start by taking a Copy of our statements.pl
00:10file, and we'll name this assignments.pl.
00:16We'll go ahead and open it up, and we'll just come in here and we'll make an
00:23assignment. And we'll change this message to print out the variable, and we'll
00:33go ahead and Save that and Run it.
00:36Now this is, if you've been going in order you have seen this in different
00:41chapters and in different contexts,
00:43you've seen exactly this construction where we assign a value to a variable.
00:48What this is, this is a statement.
00:50A statement is a set of instructions to the Perl language, and it's terminated by
00:56a semicolon. And in this case, the statement is an assignment where it assigns
01:01this value, 42, to the variable $var, using the assignment operator, which is the equal sign.
01:10And then we are able to print out the value and we see the result.
01:14We can, of course, assign different types of things.
01:16We can assign a string instead, and we can Save that and Run it, and there
01:23we have that result.
01:24Of course, we can assign different kinds of things.
01:27We can assign a list to an array, and we want to put that list in parentheses.
01:40And here we have assigned three different things: the string 42, the number, the
01:45literal number 42, and the results of an expression 40+2.
01:51Alter that list, and now what we want to do is we want to print that as a join,
01:55because that's how we print arrays, and we'll Save that and Run it.
02:06And there we have our list.
02:08So, this is, in a nutshell, how assignments work.
02:11They use the assignment operator, and when we get into the operator section,
02:17we'll see some different variations on this.
02:19But this is the basic structure of an assignment statement in Perl.
Collapse this transcript
Using statements and expressions
00:00So, let's talk about Expressions.
00:02To get started, we'll take our statements.pl, and we'll go ahead, and we'll make
00:06a copy of that, and we'll call it expressions.pl, and open that.
00:13And we'll go ahead, and we'll start by making an expression, so we'll say
00:15my$x = 42;, and we'll print that value out here in this message function. We'll just
00:24say $x, and we'll Save that and Run it, and you'll see we get a 42 down here.
00:32So, in this case, we can see that 42 is an expression that has a value of 42,
00:37and it's getting assigned to this variable, and that variable is getting printed out here.
00:40And that all seems very obvious.
00:42What's not obvious here is that this entire statement is an expression, and in
00:47fact, this entire statement is an expression, and in fact, every statement in
00:53Perl is an expression, and there are expressions within expressions.
00:58Everything is an expression.
01:01So, if we do, instead of this 42, if we were to do something like 3+7 * 10; and Save that,
01:08now what do we expect to get printed out here?
01:12Well, this would depend really on whether the addition happens first or the
01:17multiplication happens first.
01:19So, if the 3+7 happens first, 3+ 7 is 10, and 10 times 10 is 100.
01:24We would expect 100 to be the result.
01:27If the 7 times 10 is evaluated first, then that's 70, and the 3 then gets
01:33added to 70 for 73.
01:36So, our result would really depend on that.
01:39I happen to know the answer.
01:40I want to go ahead and Run this, and we can see that 73 is the answer, so the
01:45multiplication is happening before the addition.
01:48That's not what we intended to have happen.
01:50We can use parentheses to force the expression to get evaluated in a certain order.
01:56And now the 3+7 will be evaluated first, and our result will be 100.
02:02So, we'll go ahead and Run this, and there's our result.
02:06What controls this is something called operator precedence, and that's covered
02:10later in the course. And there are Charts and Tables, and you'll really get to
02:15understand that in some detail if you want to, but the important thing to
02:19remember - and I don't have the operator precedence chart committed to memory,
02:23and I don't think very many people actually bother with that -
02:26the important thing to remember is if you need for things to be evaluated in a
02:29particular order, then use the parentheses.
02:32Otherwise, if you have it like this, then whoever comes along to read it later,
02:39you may know, and you may actually mean for this multiplication to happen first.
02:44But whoever comes along to read it later may not know that.
02:47And in fact, you may not remember that a year from now.
02:50And you're going to come, and you're going to look at it.
02:52And you're going to go, um-huh, and you are going to have to pull out the table,
02:54and look at it and figure it out.
02:56It's so much easier to just use the parentheses, even if the parentheses are the
03:00default order anyway.
03:02So, let's just take a look at one other aspect of expressions in Perl.
03:08Because everything is an expression, you can do things like this.
03:14And so if this expression evaluates to false, which in Perl means it would be a
03:21zero or an empty string, then this message will be displayed.
03:26But since this does not evaluate to false, this expression here never gets
03:31evaluated, and so this message will never get displayed.
03:34We'll go ahead and Save that and Run it, and you can see that we just get the message, 73.
03:39We do not get the message, foo.
03:42If on the other hand, this were a zero and we Save that and Run it,
03:49now we get the message foo, and we get the message 1, because message happens to
03:56return true. It happens to return a 1 value, and so that's getting assigned to
04:01the x, and so we're printing out both of those values.
04:05This is an important feature, and you will see this kind of thing done all the
04:10time in Perl code that you run across and that you read.
04:13So, it's important to understand a couple of things.
04:16One, true and false - all expressions can be evaluated as either true or false,
04:22zero is false, empty string is false, and the undefined value are all considered
04:27false. Anything else is true.
04:30And we'll cover all of the different types of operators later.
04:33You can use logical operators to actually decide what code gets executed, and
04:38you can even do side effect things, like printing out a message.
04:42I don't recommend that you do that in code that anybody else is ever going to have to read.
04:46But you need to understand that it works that way, because you will see code
04:50like that and occasionally, something like this might come in handy for you.
04:54So, that is Expressions in a nutshell. Just to remember that all statements in
04:59Perl are considered expressions.
05:01They get evaluated in a particular order.
05:03You can control that order with parentheses, and you can even use that order to
05:09selectively execute code.
Collapse this transcript
Combining statements into blocks
00:00Blocks of code, in Perl, are enclosed in curly braces, and they consist of one
00:07or more statements.
00:08So, let's take a look at how that works.
00:11We'll go ahead and copy the statements.pl, and call it blocks.pl, so we don't
00:17overwrite the statements.pl.
00:19You'll find all of these in the 04 Statements folder, inside the Exercise Files folder.
00:23We'll go ahead, and we'll open that up.
00:27We'll take a look. Well, here we have a block of code, and here we have a block of code.
00:33So, anything inside of curly braces is considered a block of code.
00:39If we wanted to, we could create our own little blocks here.
00:42We can say something like if (1) and message ("this"); and message ("that"); or else{.
01:00We can put this one here in the else, if we want to.
01:04Go ahead and Save that.
01:06Of course, because we have this conditional (1) - and we'll talk
01:08about conditionals later -
01:10only this block here was the only one that will be executed, and this block will not.
01:17So, we'll go ahead and Run this, and we'll see that this and that prints, and
01:22the other one doesn't.
01:22If we make this condition false (0), then we'll see that this other one runs.
01:30So, in a nutshell, that's what a block of code does is it allows you to treat
01:35several lines of code as a unit.
01:38We will be using blocks a lot throughout the rest of this course.
01:43We'll be talking about them in our lesson on Scope, which is coming up, and all
01:47the conditionals and the loops that are coming up.
01:50So, it's good to understand.
01:52It's a very simple concept.
01:53Anything inside of these curly braces is considered a block, and it has
01:59more than one statement.
02:00If you remember, the last semicolon in a blog is optional.
02:05I strongly recommend that you use it, but you'll see that the code runs just
02:09fine without it there.
02:11Let's put a (1) in here, so that code actually executes.
02:16We'll Run that so we can see this and that.
02:19I strongly recommend that you include the semi olon, even though it's optional,
02:24because when you have more than one line of code inside of a block, you might
02:29find that you want to add another one.
02:33If you had neglected the semicolon on the line before you might end up with an
02:37error, if you forget to put it in later.
02:40So, that's what a block is.
02:42Coming up, we are going to talk about Scope, and that has a lot to do
02:45with blocks, as well.
02:46So, if you are interested in understanding blocks thoroughly, then be sure to
02:51also watch the movie on Scope.
Collapse this transcript
Understanding scope
00:00Scope, in Perl, is the concept of where things are visible from,
00:06and this is best illustrated by looking at it.
00:09So, let's go ahead and make a copy of the statements.pl file. We'll call it
00:14scope.pl and go ahead and open that.
00:19So, here we see that we have some blocks.
00:22We have this block here.
00:24We have this block here.
00:27You'll notice that in some of these blocks there are variables declared.
00:30So, here is a my $e, and that's inside that error block and my $m inside the message block.
00:39If we were to try to access m from inside of the error block,
00:44if I were to just put an m here, you'll notice that I get an error.
00:48The error says, "Global symbol "$m" requires explicit package name."
00:54That is one very creative error message, and you'll see that a lot.
00:58What that means is that you are trying to access a variable that does not
01:02exist in this scope.
01:03Of course, if they were to just say that, it would be too easy.
01:07If I Save this and Run it, which will then give me a run time error version of
01:13that, it says it's got errors.
01:15Go ahead and proceed.
01:16Global symbol $m requires explicit package name, and it gives the line 24.
01:24This is just how the interpreter interprets this, that you are trying to access
01:29a global symbol, because it doesn't have a my declaration.
01:32So, it considers this trying to access a global symbol.
01:35What that's means is if it were declared in a global scope, if I were to put a
01:39$m here, "This is variable \$m";,
01:44now we don't have an error anymore.
01:50I Save. It forces it to.
01:54Now we don't have the little red x.
01:55If we go ahead and Run,
01:58we'll see that everything works.
02:01If I call error from up here error ("message"), and I'll just say ("this is
02:09an error message").
02:11So, because we are using $m dollar down here instead of $e, it will actually
02:19print out this message from the global scope.
02:23Let's Save that and Run it.
02:28Here is 'this is variable $m.' That's this one up here in the global scope,
02:34because we used the global $m down here.
02:38This is interesting. We actually have a $m in message,
02:43but that's in its own little local scope.
02:45Because it's declared with my inside of this block, that only exists in there.
02:52When I go to access $m in this other scope, it's using the global one,
02:58because it doesn't have one declared here, and there is one declared globally.
03:03If instead, I were to call this $m instead, now we have a local $m. This $m
03:13will now be this $m using its local scope, because we have that verbal
03:19declared in local scope.
03:21Now, this error message will do what we expect it to do.
03:24It will say this is an error message, because that's what's getting passed to it.
03:28That's what's getting read in through the shift here, into this local version of
03:33$m. So, we'll Save that and Run it.
03:37There is our error message. This says, "this is an error message."
03:40That's the one that we passed with.
03:42That's what we expect to have happen.
03:44So, normally, I just have $e down here, and $e over here, so we are using the
03:51local variable, and $m is used for message.
03:56There is no global in here, and that does what we expect it to do.
04:03So, the message is the template.pl file. That gets passed to message.
04:10It gets put in this $m, which is local to this block, and it gets printed out there.
04:16The error message, this is an error message that gets passed here into the error function.
04:23It gets read into this local version of $e, locally scoped.
04:30It gets printed out like this.
04:32So, scope refers to where a variable is accessible from.
04:38Locally scoped variables exist in the local scope in which they are
04:42declared, usually in a block.
04:45Globally scoped variables are outside of any block, and those are accessible
04:51from all of the enclosing blocks.
04:54In fact, if I were to have another block inside of this block here - and we'll see
05:00examples of this later on when we do loops and conditionals -
05:04then the variables in this scope will still be accessible from those inner
05:09blocks, unless they are overwritten by having a variable of the same name declared locally
05:15inside of those blocks.
05:17So, that's how scope works.
05:20Scope is about where variables are accessible from and where things are
05:25visible from, and they tend to be visible within the blocks and enclosing
05:31blocks where they are declared.
Collapse this transcript
5. Conditional Statements
Understanding conditional statements
00:00Before we look at Conditional statements in detail, let's look generally at
00:04conditional statements in Perl.
00:06Conditionals execute code selectively.
00:09For example, in this statement, if the condition is found to be true, the
00:14statement will be run.
00:16If the condition is not found to be true, the statement will not be run.
00:21Conditionals may also provide alternative code,
00:23as in this example. Statement 1 will be run if the condition is found to be
00:28true, and statement 2 will be run if the condition is not found to be true.
00:35Statement 1 and statement 2 will never both run.
00:38It will always be one or the other, depending on the status of the condition.
00:43There are, of course, more complex examples, and we'll get into that as we get
00:47into the details of conditionals in Perl, in this chapter.
00:51One note about Perl 5.10: Perl 5.10 is as of this writing, the very latest version of Perl.
00:58It has a very few feature that are incompatible with earlier versions.
01:02So, they are covered separately in a Perl 5.10 New Features chapter,
01:08later in this course.
01:10Beginning in Perl 5.10, Perl also provides a switch statement.
01:14Switch statement uses given and when, and it is only available in version 5.10
01:20or later versions of Perl.
01:23So, it's covered separately in the separate chapter on these new features, and
01:27is not covered in the body of this course.
01:30The reason for that, of course, is that it's incompatible with earlier versions, and
01:33if you use it, and you try to run your code on a system that doesn't have Perl
01:385.10, which is most deployed systems at this point, then it will not work and it
01:44will break the code.
01:46So, this feature, along with other 5.10 features, is covered separately in
01:50the Chapter on 5.10.
01:52So, that's an overview of Conditionals in Perl.
01:54Now, let's get into the details.
Collapse this transcript
Creating conditionals with if
00:00The first of the conditionals that we'll talk about is the if conditional, and
00:07we'll start by making a copy of the conditionals.pl file, and we'll call it
00:11if.pl, so that we can experiment without overwriting the Exercise File. And I am
00:22just going to show you how if works.
00:24You've seen it before, but we're going to talk in detail about it here.
00:27So, we're just going to say if (1), and message ("this is true"), and so what
00:38this does, this is if.
00:39If is a keyword in Perl, and its purpose is to select code for
00:45conditional evaluation.
00:48And the argument to if always goes in parentheses, and if the argument evaluates
00:52to true, then the code inside the block will evaluate, and in this case, it is
00:59message (this is true).
01:01Since message is the only statement in the block, the semicolon is optional, but
01:04I like to put it there when I remember to. Sometimes I do forget.
01:08And if we save this and run it, we'll see that the message displays.
01:16If I put a 0 here instead of a 1 and save it and run it, we'll see that the
01:23message does not display.
01:26So, we know that 0 is false and 1 is true.
01:30In actuality, anything besides a 0, or an empty string, or undef is considered true.
01:38So, if I put in here 142 and Save that and Run it, we'll see that this is true.
01:47If I put in here a string and say "this is a string" and Save it and Run it,
01:56it's still considered true.
01:58If I put in an empty string - that is a string with nothing in it, and Save that
02:04and Run it - we do not get the message, because that is considered false, or if I
02:10put in the special undef value, that is also considered false. Then Run that.
02:17Any expression, at all, can go here.
02:19It can be the result of a function call.
02:22It can be any expression.
02:24It could be a mathematical expression, 5+5, and that will evaluate to true.
02:31If I say, 5-5, of course, that will evaluate to false.
02:37And so it can be anything that resolves to a value, and any value that is 0, or
02:44an empty string, or the undef value will be false.
02:49Anything else, whatsoever, will be considered true.
02:53And so that is how if works.
02:55I just want to cover one other thing that I find useful.
03:00This is certainly not required, and most Perl programmers do not bother to do this,
03:05but I find it useful, is to use the constant module to define constants for true and false.
03:12These can be useful for return values, or for anything where you want to just
03:17have something that not only evaluates to true or false, but actuality looks
03:22like true and false to the person reading the codes.
03:24So, I'm going to say use constant and this allows you to define constants in Perl.
03:30Constants are special values that cannot be modified and will always be
03:36guaranteed to be what you define them to be.
03:38So, I'm going to make 1 for True, and make one for False.
03:41And the format of the constants here is just like a hash.
03:48And so you can define however many things you want to here.
03:52And then if I put True in this, the syntax is just like that, it doesn't need
03:57quotes, or anything like that.
03:59I need a semicolon here, and then we can Save and Run, and we'll see that
04:07that evaluates, of course, true. And I can put False in here, and Save that and
04:12Run it, and that will evaluate to false.
04:17Using the constants, I find it useful.
04:19I'll use them for return values from functions, and things like that where I
04:23want something to actually say true, and say false.
04:26Perl is lacking keywords for this. Many languages have them. Many languages don't.
04:32In languages that don't, I'll tend to define constants, or macros, or whatever
04:37facility that language has.
04:38I like to have the word True and the word False in some circumstances, and so
04:43this is a convenient way to get that.
04:45So, again, this is the if statement.
04:47This is the if conditional, and it selectively evaluates code based on a
04:54condition that can evaluate to true or false.
04:560, the empty string, and the undef value are considered false. Anything else
05:01is considered true.
Collapse this transcript
Extending conditionals with else
00:00Continuing our discussion of conditionals in Perl, we're going to talk about else.
00:05Else works with If.
00:07Just make a copy of conditionals.pl.
00:10We call it else.pl. And just as a starting place here, we'll go ahead and define
00:17a pair of constants.
00:24These are just for convenience.
00:30I like to do this when I am writing code, and we'll come in here, and we'll say
00:38if (TRUE), message ("this is true");
00:47and put in an else.
00:48Now what the else does is it executes in the case that the if clause is False.
00:59So, in this case, we know that it's true because we are using our constant for
01:03TRUE, and we'll get the TRUE part here.
01:06This is true and if I change this to FALSE, we'll get the False part.
01:11Run and this is false.
01:16What else does is it allows you to have a block of code that will execute in the
01:22event that the condition for the if statement is found to be FALSE. And so the
01:28TRUE part is this first block, and that's from there to there, and the FALSE
01:33part is in the else block.
01:35Now notice that the formatting here, where I put the else on the same line
01:40as these curly braces,
01:41this is the matter of style.
01:42It doesn't have to be there. Not everybody likes to do it that way. I like it.
01:46It's concise and it's clear. But you don't have to do it that way, as you know
01:50whitespace is ignored in Perl, so you can format this however you like.
01:54The important thing to know here is that this allows you to have an alternate
02:00execution path for your conditional in the event that your expression is False.
02:06So, that is how Else works.
Collapse this transcript
Extending conditionals with elsif
00:00In addition to If and Else, there is one more conditional that we have.
00:05It's called elsif and it's really incredibly useful, and you'll be glad that we
00:10have it when you learn what it does.
00:11So, let's go ahead and make a copy of conditionals.pl and call it elsif.pl, and
00:17elsif is spelled like that without the second e. It's e-l-s-i-f-.-p-l, and we'll go
00:26ahead and open that.
00:27We are going to forgo the constant that we've done in some of the other lessons,
00:32because I think you understand that at this point, and we'll just go ahead and
00:36say if(1), and we know that one is true.
00:39So, we'll say message ("this is true") and else message ("this is not true"),
00:49and we'll go ahead and Save that and Run that.
00:51And you'll see that, of course, the one is true and if we were to put a zero in
00:56here and Save and Run that, that is not true.
01:01Now what if you wanted to have another conditional in there?
01:05What if you wanted a third choice?
01:09You can say elsif(1) and message, ("but this one is true!").
01:24And when we Run that, that's what we get.
01:26We get that third one and so these are all mutually exclusive, which means that
01:31you're only going to get one of these. And in fact, you could have as many
01:36elsif's as you want to.
01:37I am just copy this and paste it.
01:40It will always select the first one that's true, and it won't bother to run
01:45anything else. So, if this one were false - now let's make one of these
01:50different than the others.
01:57And so we'll go ahead and make this one false, and now you're going to get the
02:02second one, which doesn't look any different, but this one is true.
02:07But if you make this one false, now you'll get this one here.
02:12This one is different than the others.
02:14So, this will always select the first one that's true and, of course, if none of
02:19them turn out to be true than you get the else at the bottom: this is not true.
02:26So, elsif is great for selecting among a number of different conditions. And just
02:33to show you a working example of this,
02:35go in your Exercise Files folder to a folder called RandomQuote and in there
02:40we have a script, and this script is called RandomQuote.
02:44We'll open that, and let's just Run that real quick so you can see what it does.
02:50What it does is it gives you a RandomQuote out of a quote file, and this one is
02:56Sid Ceaser, and the quote file is here, quotes.txt, and you can see that in here
03:03is a bunch of quotes from different people.
03:07Some of them are silly. Some of them are meaningful. And the way that this
03:12works is, in a nutshell,
03:15it reads through this quotes file, and every time it sees a token surrounded in
03:22dollar signs like that,
03:24it looks at what that token is and it decides what to do based on that token.
03:27If the token says quote, then it starts a new structure to store a whole quote in byline.
03:34If the tokens says byline, it stores the byline in that structure.
03:38If it is just the text, it'll store the text in the structure based on the token
03:43that is read before.
03:45So, it will read a token.
03:47If it's a quote token, it'll start a new structure. It reads a line.
03:51It puts it into the space for that token.
03:54So, it's either the quote or the byline and it does all of this with a if, elsif.
04:02So, there's a loop here, this while loop for getting the line of text, and we'll
04:07cover loops in another chapter.
04:10But here is the if, elsif and else, and so it's getting the token.
04:15It's checking it as a token and it's doing its default, which in this case is to
04:20give an error message if there wasn't a token, but it's got some blank text line
04:23and it doesn't know where to put it.
04:26So, that's an example of if, elsif and else in a real world script.
04:31We'll go ahead and Run it again, get a different quote.
04:33Everytime we Run it, we get a different quote.
04:35Now we'll look at the script throughout the course, and we'll be looking at
04:40different aspects of it as we learn different parts of the Perl language.
04:43So, don't expect to understand the whole thing at this point.
04:46I am just showing you that this is the sort of the thing you can use if,
04:50elsif and else for.
Collapse this transcript
Building if statements with postfix conditionals
00:00One of my favorite features of the Perl language is the ability to use control
00:04structures in a Postfix notation, and this is best illustrated by showing you.
00:10You may not completely understand what I mean from just explaining it like that.
00:15So, we'll go ahead and make a copy of conditionals.pl, and we'll call this one
00:19postfix.pl. That's post, p-o-s-t-f-i-x, postfix and open that up.
00:26We'll start out by just writing a little if statement, and we'll
00:33declare a variable, and if ($x > 25 and $x < 100), we'll just display a message,
00:47("number is in range!").
00:50We'll go ahead and put in the semicolon first.
00:54We'll Save that and Run it. And because the number is greater than 25 and it is
01:01less than 100, number is in range.
01:04This is perfectly reasonable.
01:06You can write it like this.
01:08Everybody will know exactly what you mean, but there is another way to do it.
01:13And this other way to do it, I think, is pretty cool, and it looks like that.
01:20What we've done here is we have taken the conditional, and we've put it at the
01:26end of the line, and we've put the actual action that is taking place at the
01:31beginning of a line where I think it's more obvious, and so this is more
01:36succinct and in my mind, it's more readable.
01:40Its do this, if that.
01:42It's kind of the way we speak sometimes too.
01:45I don't know of any other languages, at least not any other modern languages in
01:50wide deployment, that have this postfix notation available.
01:54I think it's really, really cool.
01:56We Save this and Run it, and you'll see that it works exactly the same as the other way.
02:01This is most useful if your action is one statement.
02:05If it needs to be more than one statement you can need to wrap it in a
02:08block, and you need to put a do before that block and it just loses its elegance entirely.
02:13You can use pretty much any control structure in Perl, and as we go through the
02:17rest of the course, when we learn some of the other control structures, even the
02:20loops, you'll see that this is a useful notation in those circumstances.
02:26And another thing is that these parentheses are not necessary anymore, and
02:31they are often omitted.
02:33So, we can save this like this and Run it again, and indeed, the parentheses are
02:39required in the more normal prefix notation
02:43that we learned before. But in this case, with the postfix notation, those
02:47parentheses were not required and you often see them omitted just like this.
02:52So, that is the postfix notation.
02:54I think it's very elegant and very useful.
02:57It allows you to put the action at the beginning of the block, and it's most
03:01useful where your action is one statement and not more complicated than that.
Collapse this transcript
Creating negative conditionals with unless
00:00Another nice feature that Perl has that a lot of other languages are lacking is
00:05an Unless conditional.
00:07Unless is the opposite of If, and it works just exactly like that.
00:13So, we'll make a copy of conditionals.pl, and we'll call it unless.pl, and
00:18we'll open that up.
00:20And we'll go ahead and declare a variable. And we'll say, unless ( $x > 25 and
00:35$x < 100 ), message ("number is out of range"), and we'll Save that and Run it.
00:50And, of course, we don't get a message, because the number is in range.
00:54And if we make this 24 instead of 42, we'll see that we get number is out of range.
01:02So, this is exactly the same as If, only the condition is reversed.
01:07Unless will only run this statement if the condition is false, and if the
01:12condition is true, it will not.
01:15You'll most often see Unless in the postfix notation.
01:19So, if I take this and paste it in there, and we can go ahead and get rid of
01:27the parentheses, so we don't need those anymore in the postfix way.
01:32You'll often see this like this: number is out of range unless this condition.
01:39We'll go ahead and Save that and Run it, and you see that that works exactly the same.
01:44I'm going to show you a couple of examples.
01:46If you look in the RandomQuote folder again at the RandomQuote.pl, you'll see
01:51that this is a very, very common structure when initializing variables in a
01:57function or at the beginning of program.
01:58I'm going to initialize this file name as quotes.txt, unless one has already
02:03been provided, unless we already have the file name.
02:06We can see it in some other places down here.
02:09Here is a little error message, ("No quotes") unless $count.
02:15So, we're trying to display a random quote, but we find that we don't have any,
02:20so we just display a message that says we don't have any.
02:23It's a very common structure, and this is the way that you'll most often see unless.
02:28Doing it with the braces {}, in the structure of a normal If condition is
02:33not as common, because it looks a little bit backwards to most people, and most
02:37people don't think that way.
02:38But this is the way that you'll most commonly see it, in the postfix notation for
02:44just doing something unless it's already been done.
Collapse this transcript
Using the ternary conditional operator
00:00One final conditional that we want to talk about in our chapter on
00:04conditionals is the ternary conditional operator.
00:08That is also a very long and cumbersome name for it.
00:14So, let's go ahead and make a copy of conditionals.pl, and we'll name it ternary.pl.
00:22This one is called a ternary operator because it is an operator that has
00:27three expressions to it.
00:30So, we'll start by declaring a variable, and we'll call this n, and we'll
00:36give it a value of 24.
00:39We'll next declare another variable, and this one going to have some text in it.
00:43So, we'll call it $s, for string.
00:45I am going to use the ternary conditional operator here.
00:49I'm going to say ($n > 25 and $n < 100), and we'll put in a question mark.
01:03We'll say that it's in range if the condition is true and out of range if
01:09the condition is false.
01:12Then we can display this in the message.
01:14It looks like I made a typo there.
01:16It says it has syntax errors. Oh!
01:19missing the equal sign. There we go.
01:22See, even the teacher makes mistakes now and then.
01:24The message number is and concatenate that with this string and $s, like that.
01:34Now, what we've done here is we have declared a number, and the number is 24.
01:38So, the number is out of range.
01:40It is not greater than 25.
01:44This is the ternary operator here.
01:47So, it has a condition followed by a question mark, and then it has 2 values.
01:53Now, the first value will be returned if the condition is true, and the second
01:59volume will be returned if the condition is false.
02:02Then that will, of course, get assigned because this has an assignment
02:06expression here to $s. So, if $n satisfies the condition, in other words, if it's
02:14in range, then this string will be assigned to $s. If the condition is not met,
02:21if $n is outside of this range, then this condition will be met.
02:25So, $n is outside of the range, so what we expect is for to say number is out of range.
02:32So, we'll Save, and we'll Run and number is out of range.
02:37If we change the number and put it in range, Save and Run, this says number is in range.
02:46So, that's the ternary conditional operator.
02:51It's called an operator because it's using an expression like this.
02:55It is not a built-in function and it has three operands:
02:59it has the condition and the expression for true and the expression for false.
03:06So, that's why it's called ternary, as opposed to unary or binary.
03:11That's how it works.
03:12Now, this is the carry over from the C language.
03:14It looks a little bit complicated. When you are reading the code and you run up against this,
03:20you always have to stop and say, "Wait a minute.
03:22It's a ternary operator."
03:25Remember how it works.
03:26So, people don't tend to use it very often.
03:29More often than not, you'll see people use straight conditionals:
03:33if, else, unless, things like that.
03:36But now and then, you run into it, and now and then, it's just the elegant
03:39way to do something.
03:40So, it's a good thing to know, and that's the ternary conditional operator.
Collapse this transcript
6. Loops
Understanding loops
00:00Let's take a look at loops and how they are implemented in Perl.
00:04Loops are used for repeating code. For example, in this while loop, as long as
00:10the condition remains true, statement1 and statement2 will execute over and over again.
00:16The Perl language provides two basic types of loops.
00:19While/until loops are loops like the one you see above there.
00:25The while loop will execute while the condition is true, and the until loop will
00:30execute while the condition is false or until the condition becomes true.
00:35For/foreach loops are called iterator loops, and they are used for iterating
00:41over a series of things or conditions.
00:45So, these are the types of loops that Perl provides.
00:48So, let's go ahead and get into the details.
Collapse this transcript
Creating loops with while
00:00The most common kind of loop that you'll probably see in your work in Perl is the while loop.
00:07So, let's take the loops.pl script, then make a copy of it, and we'll call it while.pl.
00:15We'll go ahead and open that up.
00:18In this example, we have a file that we have opened, linesfile.txt.
00:24If we take a look at that file, we see it has 5 lines of text in it.
00:28We are going to use a while loop to read this file. And we'll just say while my
00:36line =, and we will use this notation to read one line from the file.
00:44We'll use a loop, and we'll print $line, like that.
00:49Now, I am not using message.
00:51I am using print because these lines will already be terminated with a new line,
00:56because of the way that this way of reading a line at a time from a file works.
01:01We'll save this, and we'll Run it.
01:05We see, we have all five lines of the file being printed there in this while loop.
01:11What while does is it executes the code inside the block.
01:16It has this block here.
01:17It executes that code over and over, as long as this condition remains true.
01:23So, the structure of it is the keyword, while, and then in parentheses, you have
01:27the condition and in this case, we have an assignment where we are assigning one
01:32line at a time from this file handle to the variable,, $line.
01:38We have declared it is a my variable, so it will be local inside the scope.
01:43Then the code inside is this one statement print $line.
01:48So, that will happen over and over as each line of the file is assigned to
01:53it, until it reaches the end of the file, at which time, this variable will become false.
01:58It will actually become undefined, the undef value, and the loop will end.
02:03It will close the file handle and be done.
02:06So, when we run it, we will Run it one more time, you can see we print all
02:11five lines of the file.
02:12So, that is the basic while loop.
Collapse this transcript
Creating loops with until
00:00Perl also has an until loop because the Perl language likes to have things that
00:05are inverse from other more common things.
00:07So, the while loop, as we learned, continues to execute while the condition is true
00:12and until loop executes while the condition is false, or until it becomes true.
00:19So, let's take a look at how this works.
00:21We'll go ahead and copy a loops.pl to until.pl.
00:28We'll open that up, and we'll take a look at the rather-backwards until loop.
00:36In this case, we are going to declare the variable first.
00:41Because everything is so backwards, this actually works out to be very
00:46convenient to do it that way.
00:49We'll type until. I am going to need another pair of parentheses here.
00:53We are going to go ahead and assign $line = a line from the file.
01:00Then we are going to test it using a regular expression.
01:03Regular expressions are covered later in the course.
01:05What we're looking for is simply whenever there is a 3 in the line of text,
01:11then this will become true and it will end the loop.
01:17So, I'll go ahead and print the line. We'll Save that and go ahead and Run it.
01:25Here, we have line 1 and line 2 and oh! We got a line 3.
01:30This condition became true and the loop ended.
01:34So, we did not print all the five lines of the file.
01:37Remember, this file here has five lines in it.
01:40So, this is how an until loop works, and it looks backwards because it is backwards.
01:46In fact, the more common way that you'll see them used is more or like this,
01:53print line until line=<FH>, file handle, has this 3 in it.
02:05You'll most often see it used postfix like this, because it just kind of makes
02:11more sense that way,
02:13because it is a backward sort of a loop and it's not how our brains normally think.
02:20So, this actually tends to make a lot more sense.
02:23This the way that you'll see it most often, especially because it's such
02:27a simple thing. We are only doing one thing, print line and then until this condition.
02:32So, we'll go ahead.
02:33We'll Save this and Run it.
02:35You'll see that it does exactly the same thing.
02:39But this is the way that you'll see it most often with this postfix notation.
02:43Again, because the until is the backwards condition from how you normally think of a loop,
02:49this might look a little odd the first few times you see it, until you get
02:53used to it.
Collapse this transcript
Iterating lists with foreach
00:00The foreach loop in Perl is an iterator loop, and it's used for stepping through
00:06a list of somethings.
00:07So, we'll go ahead and look at how that works.
00:09We'll make a copy of Loops.pl, and we'll call foreach.pl, f-o-r-e-a-c-h-.-p-l.
00:17We'll go ahead and open that up.
00:19In this example, we are not going to use our linesfile.txt;
00:23we'll just delete that.
00:24We declare a variable, my @list=, and we'll list out some strings "one", "two",
00:36"three", "four" and "five".
00:42We'll say foreach my string and we'll put in the (@list).
00:51We will message it, message ($s).
00:56So, what this does is foreach will step through every element of this list.
01:03It will assign them, one at a time, to this variable, my $s. Then using that, it will
01:10go ahead and run this block of code, which in this case, has just one the
01:15statement, the message function call.
01:18So, what it should do, it should print one on a line, all of these strings
01:22"one", "two", "three", "four", "five".
01:24So, we'll Save that and Run it, and there it is: one, two, three, four, five.
01:30So, that's how foreach works.
01:33There is a couple of interesting things that you can do with this.
01:36If you don't have the variable declaration there,
01:39then foreach will use the special built -in variable, $_, which looks like that.
01:46So, we'll Save that and Run it. We'll see that
01:49that works exactly the same.
01:50Foreach is very often used in its postfix notation, instead.
01:56So, this is what you will very commonly see, something like this.
02:04You can see that's very succinct, and its easy to read. message this foreach of that.
02:10You simply Save that and Run it, and there you go:
02:15one, two, three, four, five.
02:17So, that's the foreach loop.
02:19It's very convenient.
02:20It's very useful, and you'll find that you use it quite a bit.
02:24It's an iterator, which means that it's used for iterating through a list of things.
02:30It's such a convenient construct that before Perl,
02:34there weren't very many languages that had anything like it. And in modern
02:37languages that have come after Perl or languages that have been revised since Perl,
02:42they been starting to put something like this in them, languages like PHP and
02:48Python have a foreach loop.
02:50So, that's the foreach loop.
02:51It iterates through a list.
Collapse this transcript
Iterating lists with for
00:00The for loop is another type of iterator loop, like the foreach loop,
00:06only it's different.
00:07It's a little bit more complicated in its syntax, and it's a little bit more
00:11flexible in some other ways.
00:13So, let's make a copy of the Loops.pl, call it for.pl, that's f-o-r, for. We'll open that.
00:23We are not going to be using the linesfiles.txt again, so we'll close there.
00:30We'll create our list.
00:32We are going to need an iterator variable here, or an index variable depending
00:38on how you look at it.
00:40We'll go ahead and write the for loop.
00:43That's for $i=0, our list($i) and our $i++.
00:50That should be a semicolon.
00:53Each of these are separated by a semicolon. I'll get into the details in a moment here.
00:57We'll message($list, left bracket, $i, right bracket), and we'll go ahead and Save that and Run it.
01:10You'll see we have our list of one, two, three, four, five, "one, "two",
01:15"three", "four", "five.
01:16It's exactly what it's supposed to do.
01:18The for loop is a little bit more complicated than the other loops we've been seeing.
01:24It has three different expressions:
01:26the first one is an initializer expression, the second one is the actual
01:31conditions - this is just like a while loop as long as this expression is true,
01:37the loop will continue - the third one is the iterator;
01:41this is the thing that you change in order to step through, whatever it is you
01:46are here stepping through.
01:47This construction is familiar to C programmers, because the for loop is actually
01:52borrowed directly from C. This is exactly how the C for loop works.
01:58Each of these expressions is separated by a semicolon.
02:04Then we have the body of the loop, which is in this block here.
02:07In this case, it just has this one statement the message function call.
02:12It is calling this list element.
02:15What we have done here - this is the common way to use for loops, especially
02:19for C programmers - is we've initializes this variable as an iterator or an index variable.
02:25It's used to index the array.
02:28You'll remember, when we learned about arrays in Lists,
02:31that this is how you index an array using the dollar sign to get the scalar variable.
02:36You use the square brackets to indicate which member of the array you wanted to get.
02:44The $i, in this case, is a number.
02:47It's stepping from 0. It's incrementing.
02:51This is the increment operator, which simply adds 1 to the variable.
02:56So, this steps from zero, one, two, three, four, as does this one.
03:01You remember that arrays are indexed starting at 0.
03:04So, this is element number 0.
03:06This is element number 1, and this is element number 2.
03:10So, we could actually print out our iterator as well.
03:14Our index, "index is $i", and put a space there and then the list element.
03:21Well, this is the string concatenation operator here.
03:24Let's save that and Run it, so you can see index is 0 and we number 1; index is 1.
03:31We have number 2.
03:33Then the increment, this happens after the loop is done.
03:37It's as if there was another block here, and this code is inside of the other block.
03:43So, it happens after the block is run and before the test happens.
03:51So, it happens that in little window of time there.
03:55In this case, all that does is increments the index variable by 1.
04:01So, you can see that this is a lot more complicated than the foreach operator,
04:06which is why you'll see the foreach operator used a lot more,
04:09because usually what you need an iterator loop for is just to step through an
04:15array, or step through a list of things.
04:18So, the foreach loop is very convenient for that.
04:21The for loop, which was the traditional way to do this before the Perl language,
04:26back in the days when C was considered a high level language and applications
04:30were mostly written in Cm
04:32The for loop was the common way to do that and still a very common way to do
04:35it for C programmers.
04:38So, it comes out a little bit complicated.
04:40It's actually very flexible and powerful, and there are other ways that
04:43it's occasionally used.
04:45But you will more often see the foreach loop used in Perl.
Collapse this transcript
Using loop control statements
00:00Perl has a couple of statements that are very useful for controlling the
00:04execution of loops, and we're going to look at those right now.
00:07So, let's go ahead and make a copy of loops.pl, and we'll call this one control.pl.
00:16Open that up and go ahead and read our linesfile.txt, and we'll use a while loop.
00:22Say while my $line =, grab that from the file handle, print $line, save that and run it.
00:35And there we have our five lines in the linesfile.txt.
00:39There is the text file.
00:41It's got the five lines in it.
00:43Let's say that we wanted to print all of these lines, except we really didn't
00:47want to print line number 3.
00:48So, what we can do is we can use the next, you could say, next if line has a 3
00:58in it, like that, and what that will do is if this condition is met - the line has
01:04a number 3 in it some place - then the statement next will execute, and what next
01:10does is it just skips everything else in the block of code and goes around to
01:15the next iteration of the loop.
01:18So, save that and run it, and you'll see that it prints every line except it
01:22doesn't print the line with a 3 in it.
01:28Along with next, there is also last, which also skips the rest of the code in the
01:36block, but it does not go around the loop again.
01:39It actually exits all the way out of the loop.
01:42So, in this case, it will just print the first two, and then it will stop, save
01:47this, and go ahead and run it, and that's last.
01:52So, actually, next and last are very, very useful, where you may have a loop
01:57that you want to go through and at some point you want to not bother with the rest of the code.
02:03You need to go and reinitialize something or you find that this is just not a
02:06line of text that you need to process, or you might find something conditioned
02:12where you just need to exit the loop altogether, and you'll use last.
02:15So, those were the loop control statements, next and last, and that's how
02:19they work.
Collapse this transcript
Building loops with postfix statements
00:00One of the really nice things about the Perl language is that all of the control
00:04structures can be written postfix as well as prefix.
00:08So, we've seen a little bit of this in our coverage of the individual
00:12loop control structures.
00:14Let's take a look at this in a little bit more detail.
00:16Go ahead and make a copy of loops.pl, and we will call this postfix.pl.
00:23We'll go ahead and open that, and here you have the file open.
00:28We'll go ahead and print all the lines of the file, like this.
00:36And that is all that's necessary.
00:39That will print each line of the file line-by-line.
00:41I'll go ahead and save it and run it.
00:43You see there is the lines of our file: 1, 2, 3, 4, 5.
00:47This is our linesfile here: 1, 2, 3, 4, 5.
00:51You'll notice that this is probably the simplest loop we've written so far.
00:55It has the print statement, which is the internal function for printing and
01:01while, and just the file handle in angle brackets, inside the parentheses for the
01:06while, and that's really all there is to it.
01:10The way this works is by using as a temporary variable, Perl's default variable,
01:15it actually is exactly the same as if we'd written it like this.
01:27Save that and run it.
01:28You see, that works exactly the same.
01:32This is Perl's default variable.
01:34It's one of the special variables, and we'll cover it in a little bit more
01:37detail in the chapter on Special Variables, but this is the most common of all
01:41the special variables.
01:42This is used as a default variable in all kinds of places throughout the Perl
01:47language. And so if you don't include this assignment, then Perl just assumes that
01:53that's what you are doing,
01:53that you are assigning to the default variable.
01:56And if you don't include it here, the built-in print function actually assumes
02:01that you are printing the default variable.
02:03And so this just becomes a convenient shorthand, and you'll see this a lot in
02:07Perl, and save that and run it again, and we see that that's how that works.
02:14If we want to, we could use our own variable.
02:16We'll have to declare it first, and we can also give it a default value - that's
02:22always a good idea - and you can say print $line while $line = the file handle
02:30and that will do exactly the same thing, but it will use our variable
02:34instead of the default variable.
02:36Likewise, we can use until, and in this case, we'll go ahead and assign over here
02:43from the file handle, and we'll test this for say the line with a number
02:51three in it and go ahead and save that and run it, and you'll see this also is
03:00rather common construction.
03:02We say we're printing each of the lines, and we're loading the line here because
03:07we're using the postfix notation, and we're using until and just printing until
03:12we get to the line that says number three. And in this case, we've already printed
03:15it, and so it gets printed out that way.
03:19So, that's while and until in postfix notation.
03:22You can also foreach in postfix notation, and what I'm going to do here is I'm
03:27going to go ahead and delete all of this because we're not going to use our
03:31linesfile.txt anymore, and we'll go ahead and declare a list, my list = ('one',
03:38'two', 'three'). I am using the single quotes here because we're not
03:45interpolating. We don't need to. 'four' and 'five' and say print, and in this case,
03:53I'm going to use the default like this, because I want the new lines, and there
03:59aren't any new lines in our strings, foreach list.
04:05And that is a very simple way to do that.
04:08We'll go ahead and save that and run it, and there we have 1, 2, 3, 4, 5.
04:14Any of the control structures in Perl can be used postfix. These are some of the
04:20ones that are very common that you'll see commonly and are very powerful in this
04:25structure,.aAd you see that the action is at the beginning of the line and a lot
04:30of people like that.
04:32When you get used to these Perl-isms, they become very powerful, and of course,
04:37you'll see them very commonly when you look at existing Perl code.
Collapse this transcript
7. Special Variables
Understanding special variables
00:00The Perl language has a number of special variables that it uses for a number
00:05of special purposes.
00:08They are used for default values for functions and loops.
00:11They are used for error codes and messages, used for information about the
00:15system and its environment.
00:18There are over 70 special variables, last time I counted. Each new version of
00:23Perl seems to add a few more.
00:25You can see a full list of the special variables in the Perl documentation
00:30page called perlvar.
00:33We're going to cover just a few of the more popular ones, the more commonly used ones.
00:37But keep in mind that there is a lot more and it's not a bad idea to go ahead
00:42and review that page, just to get an idea of what's available.
00:46Probably the most common special variable is the Default Input Variable.
00:51This is used for default values from loops and things like that.
00:57Many of Perl's built-in functions use the dollar underscore variable as a default
01:03input, so that these functions can be used in shorthand notation.
01:08When we get into regular expressions, you'll see that Pattern results are
01:12available in the numbered variables, $1, $2, $3, et cetera.
01:18The System error variable, dollar, exclamation point,
01:21or $bang is very commonly used for system errors and messages. And we've seen
01:27that already in some of our examples.
01:31The errors from eval are passed in dollar, at sign.
01:36The Process ID number is passed in dollar, dollar, and the Program name is passed in
01:43$dollar 0. Lists of arguments for subroutines are in the array underscore, the at sign, underscore.
01:53Command-line arguments are in the ARGV array.
01:58Lists of paths that Perl searches for libraries and modules is available in the
02:04INC, short for include array, and the environment variables are available in a
02:11special hash variable called percent ENV.
02:15Again, these are just the most common ones.
02:17There is a very complete list in the Perl documentation, in the perlvar
02:22page. And in the next couple of movies, we'll look at some examples of how
02:27to use these.
Collapse this transcript
Using special variables
00:00Let's take a look at some examples of how special variables are used in Perl programs.
00:05The point of this exercise is to see, in general, how the special variables are
00:11used, not necessary to learn how to use specific special variables.
00:15There is a lot of the specific special variables, and it's a good idea for you to
00:19familiarize yourself at least with the list of them and then do some
00:23experimenting to learn how to use them individually.
00:26But we're going to give you some guidance here, generally, how they are used in Perl program.
00:31So, let's take a look. Go ahead and make copy of the specials.pl file.
00:36I'm going to just call this one examples.pl, and we'll go ahead and open that.
00:43And the first thing we see here is that a special variable is being used, right off the bat.
00:47This @ARGV is a special variable that gives you the command-line arguments.
00:52Let's take a look here at an example of that. And if I use message and put a join
00:59in there and @ARGV, we'll save that.
01:06Now if we run this here in the IDE, nothing will happen. And that's because there
01:10aren't any command-line arguments, and it's a little bit of a pain to get
01:13command-line arguments into the IDE.
01:15So, we're just going to do this on the command-line.
01:18How you get to your command-line will depend on what operating system you are using.
01:22So, here I am on the command-line, and I am in the 07 Special Variables folder.
01:27And I'm just going to type perl examples.pl and put some arguments on the
01:32command-line: one, two, three, four, five. And we'll run that and we see that we
01:38get one two:three:four:five, separated by colons.
01:42So, what's happened here is we've used this join function and what join does is
01:47it takes a list and it puts separators in them and returns it as a string, and so
01:51message is printing that string with those colons in between the elements of the
01:56array. And so this list here is called ARGV with the at sign, and that's the
02:02special variable that contains all of the arguments from the command-line.
02:06And so these five arguments from the command-line, one, two, three, four and five
02:12got past that special list, got joined together with the colons and printed out
02:17from our message function.
02:19So, that's how a special variable is used.
02:23Now there is another special variable, which is at, underscore, and this used for passing
02:29arguments into a function. And we've actually used it here because we've passed
02:33these arguments into the function.
02:35This is a list of arguments, @ARGV, and it's getting passed into this main
02:39function. And so inside of the function, the special variable at, underscore will have
02:45that list that's been passed in, which in this case, will be the same as the ARGV list.
02:49So, if I save this again and run it on the command-line, we'll see that we get
02:54exactly the same result, because those same elements of the array are getting
03:00passed into this function, and they are being received in a special variable
03:05at, underscore. If I were to, instead, pass a different list of strings, say six, seven and
03:14eight, like this, and save that, even though these arguments here are getting
03:23passed in, I now get six, seven and eight because I'm not using @ARGV anymore.
03:31Now I'm just using this at, underscore, which is getting this list of arguments from the
03:37function call inside of the function.
03:40So, that's the at, underscore. It's very useful.
03:43It's used very commonly for passing arguments into a function.
03:49Likewise the dollar, underscore is very common.
03:53That's the so-called default variable and so it's used, for example, if we
03:59had it for each loop, and we're looking at that at, underscore, and we go ahead and just
04:07say print, like this,
04:09what will happen is that each of the elements in this array will get
04:15printed one-by-one.
04:17This is using the special dollar, underscore, but it's invisible.
04:21We don't actually need to type it, because it's a default variable.
04:24So, if I save this and run it, you will notice that we get them without any
04:28punctuation in them here, because this is just printing them one-by-one without
04:33joining them, or anything like that.
04:35But this is exactly the same as if we had specified, explicitly, the dollar, underscore in both of these places.
04:43So, we save this and run it, and we still have that same result.
04:49So, in a nutshell, that's how the special variables are used, the dollar, underscore special
04:54variable is oftentimes not typed because it's a default variable, at, underscore is used
05:01for passing arguments into a function from a function call.
05:06And that, of course, is a list because it's got the at sign.
05:10And the dollar, underscore is a scaler.
05:12It's a one-dimensional variable because it's got the dollar sign.
05:16And so these are the most common special variables, and that's how they
05:20are commonly used.
Collapse this transcript
Working with special file handles
00:00Along with these special variables there are some other special tokens. They
00:05are actually a type of variable called File Handles, and there is a few of them
00:11that are used for different purposes in Perl. And so why don't we go ahead and
00:16make a copy of this specials.pl, and we'll call this filehandles.pl, and we'll
00:24go ahead and open that.
00:27When we run this - I'll just go ahead and run it -
00:30you see this message comes out.
00:32It says, "This is the template.pl exercise file," blah, blah, blah.
00:36And this happens with this print function down here in the message subroutine.
00:44And the print function, by default, prints out to the standard output stream.
00:50And this is a UNIX-ism, which happens to also be present in most operating
00:55systems, including Microsoft Windows, because so much of modern programming and
01:01modern operating systems is derived from concepts that come from UNIX way back
01:06in the 70's and 80's. And so there is a special output stream called Standard Out.
01:12And if I just type here Standard Out, like that, and save and run, you'll
01:19see that nothing changes.
01:21It does exactly that.
01:22So, the Standard Output stream is the default, and you don't have to specify it.
01:26But this is how a File Handle was specified in the print statement here.
01:33And if, instead, we were to use one of the other ones like Standard Error,
01:39like that, you'll see that here in Eclipse this will print in red because that's
01:45the way the standard error stream is printed here in Eclipse.
01:50If we were to do this in the command- line and if I run this script here, we see
01:59it looks exactly the same.
02:01The difference is, and where this whole Standard Output and Standard Error comes
02:06from, is that the default output stream in the console is Standard Output.
02:12So, if I put this here back to Standard Output, Standard Out, like that
02:18and save it and run it, then we have still what we expect.
02:22If I were to redirect the output to a file using the redirect operator in the
02:30shell on the command-line here in UNIX, and that's the same in Windows and in
02:33most operating systems,
02:35you'll notice that nothing came out to the screen, but there is now a file
02:40called tempfile.txt and it has that output in it.
02:45Go ahead and remove that file. And so it's not there anymore. See, all we have now
02:53is the filehandles and specials.
02:56If I change this, again, to Standard Error and try that little
03:02experiment again, I'll save it here switch to the terminal, and we will go ahead
03:07and redirect the output to the tempfile.txt,
03:10you'll see that this still comes to the screen now, because the standard error
03:15is not getting redirected. All that's getting redirected is the standard output.
03:19So, this is the purpose of Standard Error, because often times when you are
03:23running command-line programs or in programs that their output goes some place
03:27other than the screen, like for instance on a Web Server,
03:30if you are running CGI on a Web Server, the standard output stream does not
03:35always go to the screen. It sometimes going to a file, like it was in this case,
03:39but you want that error message displayed to the user.
03:42So, in this case, it always will because we're going to the standard error.
03:46And if you are in another environment, like, for instance, this clips environment
03:50or a Web Server, your error will go some place where it will look like an error.
03:55In this case, it gets displayed in red.
03:57If you are on a Web Server, it might go to the error log, so your error stream
04:01is actually important.
04:03And what I will often do is in my error function I'll have that go to standard error.
04:10So, that if we actually have an error instead of a message and I type error
04:15here and we'll make this one go to standard out, which is the default, so I'll just delete that.
04:21And if I save this and run it, now our error message comes out here and it's in
04:27red because it's going to the error stream, or if I was running this from the
04:33command-line, or I am redirecting to a file or redirecting to a pipe or some
04:37place else, I still get this error message out to the screen.
04:41So, that's the function of the standard output and standard error.
04:46A couple of other special filehandles that I want to talk about.
04:49I want to talk about a special input filehandle, and this one is a
04:56little bit different-looking.
04:57It looks like this.
04:59It's a special input handle.
05:05What it does is it takes any file names that you specify on the command-line, it
05:11opens the files and reads them.
05:13And so if I were to just make this whole script a whole lot shorter, just take
05:19out all those other stuff so the script is very, very short and save that, and
05:25then on the command-line, I'll just run this from itself, I'll just write perl
05:31filehandles.pl filehandles.pl.
05:34And so what we have here is we are running the script filehandles.pl and its argument,
05:40on the command-line, is just its own file name.
05:42And so when I do that it will actually print out the file, just like that.
05:48And so this special file handle, what it does is it takes all of the files that
05:53are specified on the command-line and it just reads them line-by-line.
05:58It's using the special dollar, underscore, like that, and so if I save that and run it, you'll
06:07see that it does exactly the same thing. It prints out the whole file.
06:13And in fact, if we wanted to, we could do something like this. That's another
06:21special variable that will print out a line number.
06:24And we'll save that and run that, and now you see we get the file with line numbers.
06:29So, that's yet one more special file handle, and this one, it's the empty file
06:34handle and it's used for getting file names from the command-line.
Collapse this transcript
Using special constants
00:00There's one final category of Special Variables that I want to share with you,
00:03and these are the special constants.
00:05They are not actually variables. They are constants.
00:08And so let's take a look at them.
00:11You can see what those look like and how you use them.
00:13Make a copy of specials.pl, and we'll call this one constants.pl, and we'll go
00:20ahead and open that. And we'll come down here to our little message.
00:25Now let's say that you wanted to just print the name of the file that
00:28contains the Perl script.
00:30You could say the file name is, and use the special constant called File, and
00:37the special constants, you can always tell them. They start with two underscores.
00:41They end with two underscores.
00:43And in this case, it's called File, and they are usually all in capital letters.
00:48And they don't need a dollar sign before them, or anything like that, because they
00:51are really not variables.
00:52They are constants.
00:53So, it's like a literal value.
00:55So, we'll go ahead, and we'll save this, and we'll run it.
01:01We'll see it says the file name is, and then this part here is all from
01:06the special constant.
01:07Now let's say we wanted to know the line number that this line of code is on.
01:13Again, let's say The line number is, and save that and run it.
01:19See, the line number is 12 and indeed, this is on line 12 in the source file.
01:25There is a couple of other ones.
01:27There is one called Package, and this is used in modules, when you are writing
01:33modules. And it's actually not used very often.
01:35It's just used if you happen to need the name of the module for some reason.
01:40And this one will say main because we are not running in an external module, and
01:44the main program is always called main and this says the line number is main. We can
01:49say the package is main and save that and run it.
01:56And finally, there is one that's called End.
01:59And what I am going to do here is I am going to put that in here, and we will get an error.
02:03And the error that we will get is that the message subroutine cannot be found.
02:11The reason for that is that this actually ends the script, and everything after
02:15this is ignored as if it were a comment.
02:18The reason for this, and the way that it's used is when you're doing pod
02:21documentation, which we'll talk about in another chapter.
02:25So, if I go ahead and save this and run it, you'll see we get this undefined
02:29subroutine main message, and you'll notice there is that package name again.
02:34And the reason for that, of course, is that it can't find this subroutine
02:39because the end of the script is considered to be there.
02:44And so these are the special constants, and that's how they are used.
02:49So, if you are looking for any of those usages, that's where you find them.
Collapse this transcript
8. Operators
Performing basic math with arithmetic operators
00:00Arithmetic operators in Perl are very simple and very much like arithmetic
00:05operators in other languages.
00:07Let's go ahead and make a copy of our operators.pl file and we'll name this
00:13arithmetic.pl and we'll go ahead and open that and let's define a variable, my n
00:26equals and we'll just say 42 + 12 and we'll print out the answer.
00:37The number is and we'll just concatenate the $n there with the string
00:44concatenation operator, which we'll learn about later.
00:46Click save and run and voila, the number is 54.
00:53So that's the Addition operator.
00:55Addition is a binary operator, which means it has two operands.
00:59In this case the one on the left is 42 and the one on the right is 12 and the
01:04result of that operator, what it returns, is the sum of the two numbers, which in
01:11this case gets assigned to this $n and printed out over here.
01:17Likewise, we have the Subtraction operator, also a binary operator with two
01:21operands, and it returns the difference between the numbers subtracting from left to right.
01:27And if I save that I'll run it, the answer is 30.
01:33Likewise, we have the Multiplication operator, which is an asterisk like it is
01:38in most computer languages.
01:41And if I save that and run it we see that the answer is 504.
01:46And finally the Division operator. Save that and run it.
01:52We see 42 divided by 12 is 3.5.
01:57Now if we just go ahead and assign the number 42 we can see a couple of other
02:02interesting arithmetic operators here.
02:05And I'll just save that and run it, and you can see that the number is 42.
02:10Now if we take this $n and put the ++ operator after it, now this is a Unary
02:17Increment operator. This will actually increment n by one.
02:21So that now the number will be 43. I'll save that and run it.
02:26Now it's 43 and likewise there is a Unary Decrement operator.
02:32It's unary because it has one operand.
02:34And I'll save that and run it and we have 41.
02:39Now a couple of interesting things about these unary operators. You can put them
02:44before, or prefix, or after, postfix.
02:48And they do pretty much the same thing but not exactly.
02:52Here you see that it incremented and made it a 43.
02:55Now if I take out this line entirely and I put that increment operator over here
03:03and save it and run it we do get 43 but if I take it and I put it here at the end,
03:11after the n in postfix notation, we'll get a different response.
03:17Now it says 42. In fact,
03:19it's still working. We saw that worked on the line before.
03:22But what it's doing is when it's postfix, it increments after taking the value;
03:28when it's prefix it increments before taking the value.
03:31So if I print this line again you'll see that I'll get 42 and then I'll get 43,
03:43because the increment is happening after this first value is taken.
03:47If I put it beforehand and save and run, we'll see that the increment happens before.
03:54So the numbers are the same in both places.
03:56So that's the interesting thing about the unary increment and
03:59decrement operators.
04:01In the prefix notation the increment or decrement happens before the value is
04:05taken and in the postfix notation the increment or decrement happens after
04:10the value is taken.
04:12So those are the arithmetic operators. We have the simple four function
04:16arithmetic: addition, subtraction, multiplication and division.
04:20And we also have the unary increment and decrement operators that can operate
04:24either prefix by incrementing or decrementing before the value is taken or
04:29postfix by operating after the value is taken.
Collapse this transcript
Creating conditionals with comparison operators
00:00Comparison operators are often used in conditional statements.
00:04So, we'll take a look at the comparison operators in Perl now.
00:08We'll make a copy of operators.pl.
00:11We'll call this comparison.pl.
00:14We'll go ahead and open that up, right here.
00:17We'll just delete this and create a conditional.
00:20Say if, I'll just put a 1 in there for now. We'll put something else there in a moment.
00:26Message, this is true, and we'll have an else here and we'll say
00:33message("this is NOT true").
00:37Now we'll take a look at some conditional operators.
00:40If I were to say, for example, 5 == 5, and you'll notice that double equal sign.
00:46That is the equality operator for numbers.
00:51I save that and run it and we'll see that is true.
00:56If I test for inequality with the not equals and save that and run it,
01:03we'll see this is not true.
01:06So the double equals sign or the bang equals, exclamation point equals, these
01:12are equality and inequality, or equals and not equals, for numeric operators.
01:18Likewise, we can test for less than or greater than, the less than operator, and Eclipse
01:25goes and tries to match that bracket there.
01:27So 5 is not less than 5.
01:29If I save that and run it, we'll see that is not true.
01:34Now 5 is less than 6, so I save that and run it, we'll see that is true.
01:42Likewise with the greater than, 5 is not greater than 6.
01:47So I save and run and see this is not true.
01:50Or if I make it 6 is greater than 5, we'll see that of course is true.
01:58See if I run that, that is true.
02:03We can check for greater or equal to, like that, and that of course will be true.
02:11We can check for less than or equals to and Eclipse will do all kinds of things
02:17with that, <=, like that. save and run.
02:23That is not true.
02:25Likewise, there are separate comparison operators for strings.
02:28I have six equal to five, so we see the eq letters.
02:39So for strings, we use letters, and you can remember it like strings are made of
02:43letters and numbers are made of symbols.
02:47So we use the letters eq for equals to.
02:50Six, of course, is not equal to five.
02:52So if I save and run that, see that's not true.
02:55But if I put the same string on both sides, save and run, we see that is true.
03:02If I try four and five, this is interesting.
03:09I say four is greater than five.
03:14We'll see that, in fact, this is true because four is after five alphabetically.
03:22Four is less than five, like that.
03:26That of course is not true, because this is comparing alphabetically.
03:33So, we also have the not equals, ne for not equals.
03:38Of course those are not equal, so we have this is true.
03:43So in a nutshell, those are how the comparison operators work in a
03:49conditional statement in Perl.
03:50There are a few other comparison operators.
03:54If you would like to see the complete list, you can look in the
03:57Perl documentation.
03:58I'm just going to press the right mouse button here, anywhere on the screen,
04:03and Eclipse with EPIC installed, just click on Perldoc and you get a little search thing here.
04:08So you search for perlop and you get a complete page on all of the Perl operators.
04:14Let me just maximize this here, so you can see it.
04:18It's actually very long and thorough.
04:22It has all of the operators listed.
04:24We're going to go through most of them in this chapter.
04:26We'll go through a lot of them anyway, the major ones, the ones that you'll
04:29use the most often.
04:30But if you want the complete list and complete documentation, that's where
04:34you can find it.
Collapse this transcript
Combining conditionals with logical operators
00:00Logical operators in Perl are also used in conditional statements.
00:05So we're going to take a look at that here.
00:08So we'll make a copy of the operators .pl file. I'm going to call this one
00:13logical.pl and we'll open that up, go ahead and set up our conditional again
00:23here, if, I'll just put a 1 in there for now and message this is true, and else,
00:35message this is not true.
00:38Now I'm going to be putting some expressions in here. I'll make a little bit of space.
00:45First thing I want to do is even before we do that is I want to show you the
00:53results of a logical expression and we were looking at comparison operators here
00:58in another lesson here in this chapter. So if I say $x = 5 = 5-- So now I'm
01:06going to put parenthesis around that and see if the parser likes that a little better.
01:13Oh I need a "my" there, there we go.
01:17So what we have here is a logical expression, this is testing for equality, and
01:21the result of that expression is true.
01:25So if we print the result, x is $x, we'll also get that this is true because we
01:33have that if(1) there. We'll just save this and run it.
01:36x is 1 because that is the result of this true.
01:42Perl uses 1 for true and if I say 5 is not equal to 5, this is now going to be
01:47false and we'll get a different result.
01:51And it says x is blank and so what that is, is that's the empty string.
01:55If I go ahead and put single quotes around that, you'll see that is an
02:01empty string. Run that again.
02:03Of course, there's several different possible values for false, a lot of
02:07even possible values for true in Perl, but when it takes the result of a
02:12logical expression, it uses this one and the empty string as the defaults
02:19for logical values.
02:22So we're going to take some logical values here and I'm just going to go ahead
02:26and use expressions at first.
02:27So we'll say 5 equals 5, so we know that that is true or 6 equals 6.
02:38So if either of those are true then the result will be true, all right.
02:40So I'm going to save that and run it and in fact we get this is true.
02:47If I say 5 equals 6 and we know that this is not true but I still have this OR 6 equals 6.
02:53We'll run that and we see that it's still true.
02:57If I say 5 equals 6 or 6 equals 7, now we know neither of these is true, so the
03:04whole or expression is not going to be true, so we'll save that and run it and
03:10we have this is not true.
03:12So this is a logical operator.
03:16The common logical operators are OR and AND.
03:20So I'm going to try the AND version. That's two ampersands.
03:24The two vertical bars is OR;
03:26the two ampersands is AND.
03:30So we'll save that and run it and of course that is also not true.
03:35So OR and AND are binary operators.
03:38For OR to be true either the left- hand or the right-hand has to be true.
03:45For AND to be true, both the left-hand and the right-hand have to be true and
03:53there's two forms of OR and AND in Perl.
03:57There's the high precedence and the low precedence.
04:01This is the high precedence version and so when you're using the high
04:05precedence version and this is the one you'll see the most often because it's
04:08been around the longest,
04:10you really need to use parenthesis on your expressions on either side.
04:15If you don't use the parenthesis on either side, you might end up binding things
04:20differently than you expect to bind them.
04:23And so generally I recommend for when you're using it in a purely logical state
04:30that you use the low precedence version and those are the words AND and OR.
04:36And so if I use an AND here, I get exactly the same result, which says that this is not true.
04:42If I go ahead and make this true, 6 equals 6 and 7 equals 7, we know that that's true,
04:50so we save and run and we get that that is true or use simply the word "or"
04:56and save that and run it and we see that that is also true.
05:03Now, when would you want to use the other kind?
05:06There is a special case here. The high precedence logical operators can be
05:12used in a different way.
05:14I can say something like my $s equals and let's just give it a variable.
05:23We'll say ARGV sub 1 or default.
05:31Now this is a very common construction here.
05:34We'll go ahead and message this out and what this will do is it looks at
05:40ARGV sub 1 and if it is not true, in other words, if it's an empty string or if it's
05:48an undef value or if it's anything that doesn't evaluate to true, then the other
05:53side of this OR will be evaluated and the result is returned to the string.
06:01This was done this way because it was a very common way to do things in shell
06:04scripts before Perl was around.
06:06It's kind of a shorthand that was very common for programmers back then and
06:11you'll still see it today. In fact I use it quite a bit in my scripts.
06:16In cases where what you mean is actually "do a logical operation," I will tend
06:23to use the word versions. They're a lower precedence, they're a lot more
06:26reliable in those kinds of situations, and in situations where I actually want
06:32to take the value and do something with it, I'll use the symbolic versions
06:36because they're high precedence, they bind tightly and they tend to work really
06:41well in these kinds of situations.
06:44So it's good to know about. Now let's take a look at an example.
06:48If you look in the RandomQuote script down here in the RandomQuote folder,
06:51I'll just go ahead and open this up and we'll look in some of these and
07:00sure enough there we have one.
07:01If we look at the error function down here, my $e = shift || 'unknown error' and
07:08so what this will do is if error is called without an argument then this shift
07:13will turn undef and the OR will be invoked and this side of the expression will
07:18be evaluated and it'll be returned to the e and so what will happen is this
07:22becomes like a default value.
07:25You'll see this kind of a construction very often when you're looking at
07:29other people's code and you'll find when you get comfortable with it that
07:32you'll use it a lot too.
07:33It's a nice shorthand.
07:34It's very quick and easy and it's really clear once you understand the
07:38paradigms involved.
07:40So I'll go ahead and close that and we'll close that and coming back here to logical.pl.
07:49Just in summary.
07:50You have two different ways of doing the logical operators.
07:53You have the letter version, which are commonly used for the pure logical
07:59evaluation and you have symbol version, which can be used in that context as
08:03long as you're using parentheses or it can be used for an alternate value, in
08:09the case where you may not know if a variable has a value in it or not.
08:14So these are the common ways that the logical operators are used.
Collapse this transcript
Reading file metadata with file test operators
00:00File test operators are a little bit different.
00:03They look a little bit different than some of the other operators and they might
00:05be unfamiliar to you unless you've done some shell programming in UNIX in which
00:09case they would be familiar because that's where they come from.
00:13Let's go ahead and take a look.
00:15We'll make a copy of the operators.pl file and call it filetest.pl and we'll
00:24open that up and I'm going to go ahead and start by grabbing a listing of the
00:33current directory, all the files in the current directory. Do that like this and
00:41this is another little special operator.
00:44This is the directory listing operator. Actually that asterisk in there
00:47is just a wild card. I could, if I want everything that starts with a D,
00:50I could do that.
00:52We just do this and this is a very common thing in Perl.
00:55It just gets a quick little directory listing.
00:58There are other ways to do with modules and object oriented programming but this
01:02is quick and easy and it's a special variable that's also an operator.
01:07You'll see that construct now and then.
01:10So we'll go ahead and step through this for each, my file name, of that dirlist
01:17and message($fn). Go ahead and save that and run it and you'll see we have a
01:24list of this directory and it's got all the files you can see them also listed over here.
01:29I've created a directory and this directory
01:32is just an empty directory.
01:33We'll look at this in the Finder on this Mac.
01:37You'll see there is an empty directory with little folder symbols.
01:40Some people call them folders, some people call them the directories.
01:43Older folks who have been around for a long time tend to call them directories
01:46and the newer folks who have been just using computers for a few years tend to
01:49call them folders because that's a relatively new way to refer to them but we
01:54have three plain files in here and one directory.
01:57So we'll close that and we can see that listing here.
02:00Now in our program we want to know that which of these are plain files, which of
02:04them are directories, maybe how big are the plain files, maybe the permissions
02:08of the files, things like that.
02:10We use the file test operators for that.
02:12So what I can do here is I can say if dash f, fn and that will tell me if it's a
02:19plain file and fn is a plain file and else message $fn is something else.
02:33If I go up to the screen there and save that and run it, you'll see that a
02:40directory is something else and the other one is our plain files.
02:44So I want to also test maybe for directories.
02:47So I can do an elsif( -d $fn ) and that will tell me if it's a directory.
02:53I'll just go ahead and copy this line, because a lazy programmer is a good programmer.
03:02I'll call that a directory, save and run.
03:09So directory is a directory, filetest.pl is a plain file, and those are all like that.
03:16There's something else of course. In a UNIX file system and a Mac is a UNIX file
03:20system, you might find symbolic links, you might find named pipes, you might
03:24find other types of things and there are tests for those.
03:28We don't use them very often and we're just going to cover the really common ones here.
03:32If you want to see a complete list just highlight this -f here and bring up the
03:37Perldoc and we'll maximize this and you can see an entire list of all of the
03:43different file test operators and you can see there are quite a lot of them.
03:47A lot of them refer mostly to UNIX file systems and some of them apply in other
03:52places as well and it doesn't hurt to use them in other places.
03:56You can get things like permissions.
03:57You can get things like symbolic links and such.
04:01For example, if we wanted to get the size of a file here we have in the plain
04:05file section, we already know because we've tested here that inside of this
04:09block we have plain files only.
04:12So I can say my $size =-s $fn like that and that will give me the size and I can
04:20put it in parentheses here and I can say $size bytes and if we save that and run it
04:28here, we'll see that we have a number of bytes for plain files.
04:34So those are the file test operators and that's how they work and how you use them.
04:39Again these are the really common ones and if you want a complete list then you
04:43can look in the Perl documentation for a complete list of all the different file
04:47test operators that are available in Perl.
Collapse this transcript
Creating a sequence with the range operator
00:00The range operator is very useful and a little bit unique to Perl and so we'll
00:06go ahead and take a look at how that works.
00:09We will make a copy of the operators.pl file, we will name it range.pl, and
00:15we will go ahead and open that and there we will put a print foreach 1 through 9.
00:26And you'll notice the dot dot is a range operator.
00:30It's a binary operator, so it has an operand on the left and an operand on the right.
00:35And what it does is it returns a list of all the elements, starting with the
00:40operand on the left and ending with the operand on the right.
00:43So in this case, it will return this list of numbers 1 through 9
00:46and it will print them all, all on one line.
00:50We'll save that and run it and there is our numbers of 1 through 9.
00:57The range operator can be used for letters as well as numbers. If I say
01:02'a' through 'z' and save that and run it,
01:08you will see we get all the letters a through z.
01:11In fact, because it's a list, we can say comma and then another range. And use 'A'
01:18through 'Z' and save that and run it and we get all of those.
01:26If we wanted just all of the hexadecimal digits, we could say 0 through 9 and 'a'
01:34through 'f' and save that and run it.
01:41Now we have all the hexadecimal digits. Let's say we wanted all the two digit
01:47numbers, for use say in dates. Let's say '00'
01:51through '31' and let's go ahead and print a join of this instead of a foreach.
02:02Join with a comma and a space and we'll go ahead and put that inside up there.
02:12And we need a comma there, don't we?
02:13We'll save that and run it and now we have all of the numbers.
02:20And you'll notice that they have their leading zeros because Perl was able to
02:24figure out that that's what we wanted, from the way we set this, '00' through '31'.
02:31So that's how the range operator works.
02:33It's incredibly useful.
02:35You'll see it a lot in Perl.
02:37You won't see it anywhere else.
02:38I am not sure if there are any other languages that actually have a range
02:42operator or one that works like this.
02:44If they do, I haven't seen it, but in a nutshell that's the range operator and
02:50that's how it works in Perl.
Collapse this transcript
Combining strings with the concatenation operator
00:00We are going to talk about the string concatenation operator.
00:03We've used this quite a bit throughout the course already, but I just wanted to
00:07pay a little bit of attention, and make sure that we understand exactly what it
00:11is and how it works.
00:13So we'll start by making a copy of the operators.pl file, and we'll just call
00:17this concatenation.pl.
00:21And we'll open that up and in a nutshell, if I were to take this string just say
00:29"string one" and dot and "string two,"
00:34these two strings, a dot is the concatenation operator.
00:38Let's save that and run it. These two strings will be run together and you'll
00:43notice there is no space at the beginning there and there is no space at the end there.
00:47So there will be no space between those two words, string one and string two, and
00:56so that's what the string concatenation operator does.
00:59Now of course, if we put a space here and we can even put another type of a thing here.
01:06We can just put the number 2.
01:07The string concatenation operator will still work, because it will simply use
01:13this 2 as if it were a number.
01:14We'll run that and we have string one and had a space and a 2.
01:20So the string concatenation operator is one dot. Of course it will work
01:24with variables as well.
01:26my $s1 = "string 1" and my $s2 = "string 2" and then we can here and simply
01:33say ($s1 . $s2).
01:46And if we save that and run it, again there will be no space between them.
01:51String 1 and string 2.
01:54A lot of times you'll see something like this, where they will just
01:58concatenate in a space.
02:00You can string as many of these together as you want.
02:03And we'll run that and then that will have a space next to it as well.
02:09So that is the string concatenation operator. It's very simple.
02:12But it's worth learning about and it's worth understanding because you will
02:16use it quite a bit.
Collapse this transcript
Streamlining strings with quote operators
00:00There are some special operators called quote operators in Perl and again I
00:04don't know of any other languages that have anything like this.
00:07We covered them briefly in the chapter on strings, in Chapter 3.
00:13We are going to cover them here again a little bit more focused like.
00:16And we'll start by copying the operators.pl file to quoteop.pl.
00:22Open that up.
00:26We will take a look at this string here.
00:29You will notice that it has these quote marks at the beginning and the end.
00:32If we wanted to, say, put this template.pl in quotes,
00:37if I were to just put in a quote mark there and a quote mark there, this is not going to work.
00:43You'll notice we'll get a syntax error.
00:45We got one right there.
00:46It says Bareword found where operator expected.
00:49And that would be this Bareword here. Because these quote marks are actually
00:54terminating the string.
00:56One solution, and this is a solution that most languages use, is to put a
01:00backslash before each of the quote marks.
01:02This is called quoting the quote marks.
01:05And what that does is that tells the Perl interpreter to not consider that the
01:11symbolic quote mark, but simply consider it the character the quote mark.
01:17In other words not to interpolate it, not to interpret it, but rather just to
01:21put in the literal quote mark.
01:22And if I save that and run it, we get the quotes there.
01:28But Perl has what I consider a more elegant solution and that would be to
01:32replace these quote marks with a quote operator, and that would be the q
01:38followed by any symbol whatsoever.
01:40So I'll just use a square bracket and I'll put another square bracket over
01:45here, and what this does is this q is the quote operator and it's followed by a symbol.
01:53You can use a slash.
01:54A lot of people would use a slash.
01:55I'll often use curly braces.
01:57You can really use anything that you want.
01:59I'll show it to you with a slash.
02:01That's a very common one to use.
02:04And if I save that and run it, you'll notice that we get the string exactly as we expect.
02:11I often use curly braces.
02:14The idea is to use something that you're not likely to use in a string.
02:19Save that and run it and that's how that works.
02:22Now just like there is two different kinds of quotes, there are single
02:25quotes and double quotes, there are single quote operators and the double quote operators.
02:30And the difference is exactly the same.
02:32The single quote operator with a single q does not interpolate.
02:36So if I have a variable up here, $x = 42, semicolon, and I go ahead and put that in here,
02:46I put it in parenthesis, $x, like that.
02:51And I save this and run it.
02:54With the single quote, we'll actually get the letters $x. With the double quote,
02:59and that would be having two qs, qq for the quote operator.
03:04Save that and run it.
03:05It actually interpolates that $x and puts in the $42.
03:09This is the same as using double quotes versus using the single quote marks.
03:14So the quote operator is very useful and you'll see it used a lot in Perl.
03:19Some people just go ahead and use them all the time for all their strings.
03:22I just use it where it seems to be necessary.
03:24A lot of times if I want to include some HTML, you know if I wanted to say p
03:29class= "example" and put this all in a paragraph like that.
03:36You know then I can get that and I get those quote marks, and I'll often times
03:40use this qq for something like that.
03:43And when I run it you'll notice I get that full HTML and I get the quotes just
03:48where they belong and everything and it just works out really great.
03:52So that's the common usage of the quote operator and you see you have got the
03:58double quote operator and the single quote operator, just like you have double
04:02quotes and single quotes in Perl.
Collapse this transcript
Understanding operator precedence
00:00We're talking about operators. We need to talk about operator precedence.
00:04And we've covered this a little bit in some of the other parts of the course,
00:08but I want to talk about it very specifically here.
00:10So let's go ahead and make a copy of the operators.pl file.
00:14I'll call this precedence and you get extra points for spelling on this one.
00:22Go ahead and open that up and we are just going to make an expression here, say
00:29my $n equals and we'll say 3+7*5.
00:38And we will print out $n. Now the point here when we save this and run this
00:45which we'll do in a moment.
00:46Let's go ahead and save it now.
00:49The result will depend on if you do the multiplication first or if you do the
00:53addition first. If you do the addition first, 3+7= 10*5=50. If you do the
01:00multiplication firs,t 7*5 is 35+3 is 38.
01:06So which is the answer going to be?
01:08I'll go ahead and run this and we'll see that the answer is 38.
01:11So the multiplication happens before the addition.
01:15If you want it to be the other way around you need to use parentheses.
01:23And now you'll get the number 50.
01:27Obviously it's a good idea to use parentheses any way, but now and then you'll
01:31see code that doesn't use the parentheses and you are going to want to know by
01:35looking at it and not having to experiment which is it.
01:39Operator precedence is how you know which it is.
01:44Here we have a chart of operator precedence in Perl and you'll notice as we look
01:51down the chart here,
01:53first you have terms and list operators.
01:56Lot of these operators you haven't seen because a lot of them are a little bit
02:00obscure or about subjects we haven't covered yet. If you look down towards the
02:04bottom, the last two, you'll see in the last one of course is the plus and the
02:09minus and the dot, which is the concatenation operator, and above that is the
02:15asterisk which is multiplication and the slash which is division and the
02:19string repeat operator.
02:21So you can see from this that the multiplication is indeed a higher precedence
02:27than the addition, and as a result that multiplication is going to happen
02:31before the addition.
02:32So what we have here is a list of all of the different precedents.
02:38We are not going to stop and talk about all these. We haven't actually covered
02:41all of these operators and some of them we're simply not going to go into detail
02:45on because they are just not used often enough.
02:49But in the Exercise Files Chapter 8 operators directory you'll see this entire
02:55table in Operator Precedence.txt.
02:57I'll go ahead and I'll maximize this.
03:00And you have this entire file in a nice little text file that you can look at on
03:05your computer. You can print it out and set it down next to your computer.
03:08It also exists in the Perl Op documentation page that we looked at earlier in
03:15the Perl manual, and so this is a useful little table to have.
03:21You'll notice in this table in the first column you have the associativity,
03:25which is left, right, or non-associative.
03:29And in the right column you have what the name of the operator is or the
03:33symbol of the operator.
03:34The associativity is which direction the operands are evaluated.
03:41Like for example if we go down here to the multiplication and addition, these
03:46arithmetic operators, you'll see that their associativity is left.
03:51And what that means is that the left operand, they're binary operators, and so the
03:56left operand is always evaluated before the right operand.
04:00In most cases that isn't really going to matter to you, but sometimes it will,
04:06and so it's just good to know.
04:08So operator precedence is an important thing to understand.
04:12Most of the time it's a really good idea to simply use the parentheses when you
04:20care about the order in which things are evaluated.
Collapse this transcript
9. Regular Expressions
Understanding regular expressions
00:00Regular expressions represent a very powerful pattern matching language, often
00:06called regex or in the plural regexes.
00:09Regular expressions are usually used within other languages like Perl or PHP or
00:16Python or C or some other language which will control the flow of the program,
00:23while the regular expressions themselves are commonly used for
00:27search-and-replace operations within the language.
00:31Regular expressions can be very simple or they can be very complex.
00:35The language itself is compact, so it can look very intimidating even when
00:42it doesn't need to.
00:43For example this regular expression here is used to extract the hours, minutes,
00:49and seconds from a time string, or this regular expression here is used to
00:55insert commas into a string of numbers so that it can be read in thousands,
01:00millions, billions, with the commas.
01:03So the regular expressions themselves are actually very simple but because the
01:08language is so compact they can look fairly intimidating.
01:12So let's go ahead and learn more about how regular expressions are used in Perl.
Collapse this transcript
Searching and replacing text with regular expressions
00:00The most common use for regular expressions is to do search and replace operation.
00:05So let's take a look at how that's done in Perl.
00:09We'll start by making a working copy of the regex.pl file and we'll name this
00:15search.pl. Go ahead and open it up and take a look.
00:19You'll notice that what this file does is it opens a file called short.txt and
00:26it reads it and prints it and then closes it.
00:29And that gives us something to work with as we experiment with the
00:33regular expressions.
00:35So let's go ahead and run this and you'll see that it prints out this short.txt file.
00:42And what this short.txt file is, is it's just a few paragraphs that have been
00:46taken out of the Perl regular expression manual, which the entire text of it is
00:52here also in the same folder, and this is the Perl regular expression manual.
00:57It's quite long, and so I thought I just take a few paragraphs from it and we
01:01could use that to work with our experiments here in this lesson.
01:05So for example if we just wanted to look at all the lines that had the word
01:08regular in them, we could say print if and put in a pattern match here for the word regular.
01:15And this is what a pattern match looks like in Perl and if we save this and run it,
01:21 we see we just get these five lines that have the word regular in them.
01:26So the two slashes here on either side of the word regular are the pattern match
01:31operator and what's between them is called the pattern, and the pattern is
01:35expressed in regular expressions and the simplest form of regular expression is
01:39just to put the text in there that you are looking to search for.
01:42The pattern match operator with the two slashes is actually a shorthand.
01:47The full version has the letter M at the beginning to indicate that it's a
01:52pattern match operator.
01:54When you don't have the M then you have to use slashes if you want to use this operator.
02:00If you do use the M, then instead of the slashes you can use any matching
02:05character that you want. For example we could use vertical bar.
02:09The reason we would want to use a vertical bar instead of the slashes is in case
02:15we wanted to search for slashes.
02:16So if I had a slash in the middle here, now I am searching for slashes.
02:21If I would use the slashes instead and put a slash in the middle, then you see
02:27we get an error, because Perl doesn't really know what that means. The three
02:33slashes is not something that it's familiar with.
02:36We can do what's called escape the middle slash by putting a backslash before it
02:41and then Perl understands it.
02:43The backslash simply means don't interpret the next letter. Use it literally.
02:48And so that allows us to search for a literal backslash inside the slashes.
02:52But the more common way to do that if you want to search for slashes is to use
02:56the M and use a vertical bar or one of the other available delimiters and then
03:01search for the slash like this.
03:04If we save that and run it, you'll see we find the two lines that have slashes
03:09on them in this file.
03:11So that's how we do the basic pattern matching for the regular expressions in Perl.
03:17One other thing that you need to be aware of here is that we're actually
03:21matching the default variable, the $_. So this is the equivalent of doing this.
03:31So the dollar underscore, if we don't specify a variable, the dollar underscore
03:36is presumed, and if we are presuming the dollar underscore, we are also
03:40presuming the pattern match operator because we are using pattern matching here.
03:45This is the pattern match operator and if you're specifying your own variable
03:49like for example if I were to say my $line, then I would have to test for line,
03:55matches this pattern, and then we use the pattern matching here.
04:00So the pattern match operator is this equals with the tilde, the little character
04:06to the left of the 1 on your keyboard with a Shift, and that's the tilde,
04:11the little curly line there.
04:13And that's used with the match operator or it's used with the substitute
04:18operator that we are going to look at in a moment.
04:20So if we save this and run it, you'll see that it does exactly the same thing.
04:25We got that error because we're printing the dollar underscore.
04:29So I have to also print the line there instead, save that and run it.
04:35Now we get just lines with the slash in them.
04:38So let's take a look at how we would do a replace operation instead, so from print line.
04:45And then I want to do a replace, I would say line and use the pattern match
04:49operator and then I use the substitute operator, and the substitute operator has
04:54two operands and they are all separated by the slashes or a vertical line or
04:58whatever match character you want to use there.
05:00And let's say I want to substitute or replace where the word regular is and
05:05call it Bob instead.
05:06I am going to use all caps for Bob, so that it's really easy to see.
05:10So if I save that and run it,
05:13now we get the entire file and every place where it said regular before we have BOB.
05:18So this is now Bob expressions, Bob expressions, Bob expressions.
05:25So that's how you do a search and replace.
05:28So the S is for substitute and this is the pattern to match and this is what it
05:33will get replaced with.
05:35So for example if we wanted to replace every occurrence of the letter A with
05:38Bob, then we could do it this way and if we save that and run it, we'll see it
05:43doesn't do quite what we expect.
05:46We still have a number of As.
05:49So there's an A and there is an A.
05:53So what it did is it basically got the first A on every line, but it didn't get
05:58all the rest of them.
06:00That's because when Perl does a search over or a substitute, which is the word for replace,
06:07it really just searches for the first one and then it goes on to the next line.
06:11If you want it to actually match and replace every occurrence on a line, you
06:17have to use the modifier at the end of the expression and the G, which stands
06:23for global, will allow you to do it for all of the occurrences in a line.
06:28So we'll save this and run it.
06:31Now we see we have Bobs everywhere where there had been an A before.
06:36So this is the basic function of regular expressions in Perl.
06:41We know how to match lines using the match operator and we know how to
06:48substitute using the substitute operator and we know about the pattern match
06:53operator, which is used to bind a regular expression to a variable.
06:59That's how regular expressions are used in Perl.
Collapse this transcript
Extracting matches with parentheses
00:00Sometimes when you are using regular expressions, you'll want to extract
00:03individual matches out of the regular expressions, sometimes more than one match
00:08from the same expression.
00:10And we are going to look at how you do this using parenthesis in the
00:13regular expressions.
00:14So we will start by making a working copy of regex.pl and we will call this one extract.pl.
00:25And we will open that and we are not going to use this file in this movie.
00:30Instead we are going to use a pattern of time, 05:24:37, and so we have
00:39got hours and minutes and seconds and we'll be extracting that.
00:47First we will match it in a regular expression with the header match operator
00:53and the match itself will be (..):(..):(..).
01:02Now the dot matches any character. It's a wildcard.
01:05We will talk about that in another movie in this chapter, and the colon
01:09matches this colon here, and this colon matches this colon here, and what we
01:14have is a very simple regular expression that will match two characters on
01:19either side of these colons.
01:22We have the parenthesis here so that we can extract these matches.
01:27When you put the parenthesis around there that allows you to extract that part
01:31of the match from the regular expression.
01:34And there are two ways that we can do this.
01:36One is to say my $hour = $1, my $min = $2, my $sec = $3.
01:48So $1 holds the value from the first parenthesis, $2 holds the value from the
01:54second parenthesis, and $3 holds the value from the third parenthesis.
02:00So we go ahead and print this out with message and say hour is $hour, and minute
02:07is $min, and second is $sec.
02:12And when we run this, save and run, we will see that we have successfully
02:19extracted all of these values.
02:21The hour is 05, the minute is 24, and the second 37.
02:27In some cases, this is really going to be the best way to do it because of the
02:31way your code is constructed where you'll be extracting these different values.
02:36But a lot of times, it's easier just to do it directly without even using
02:40the $1, $2 and $3 notation by declaring your variables like this in a list,
02:52and simply assigning it this way, and that's because this whole pattern
02:58match construction returns a list of the values in these different
03:03parenthesis in order.
03:04So in this case it will return a list with 05 in the first element, 24 in the second
03:09element, and 37 in the third element and those will get assigned respectively to
03:14hour, minute, and second and our printout will work just fine.
03:18So we'll save this and run it, and we see that we get exactly the same result.
03:23So those are two ways to extract. Use the parenthesis to indicate which
03:30parts of the pattern you want to extract, and they will be returned as a list so
03:36that you can assign them directly to a list of variables, or they will be
03:40returned in the $1, $2, and $3 variables so that you can use those instead.
Collapse this transcript
Matching wildcards
00:00Sometimes when you are matching things with regular expressions for searches
00:04and replaces, what you are matching might not be entirely specific and for this
00:09we have what are called metacharacters or wildcards in the regular expression language.
00:15So lets take a look at how that works.
00:17We'll start by making a working copy of regex.pl and we will call wild.pl.
00:24Go ahead and open that.
00:26And we will be going through the short.txt file again.
00:29Let's just say we want to print out the first four characters of every line.
00:35So we will start with our matching operator and we will match the beginning of
00:39the line, which is matched with the caret metacharacter.
00:44The little up arrow there. And that matches the beginning of the line and then
00:49the dot character matches any character.
00:52So we will just match the first four of those and we will put that in
00:56parenthesis so that we extract it, and we will print this a message and we'll
01:02say $1 if $1, and that's because there are maybe some lines where there aren't four
01:08characters at the beginning of the line.
01:10So we'll go ahead and save that and we will run it.
01:15And there's the first four characters of the lines that have four characters at
01:19the beginning of them.
01:21Maybe we want to look at the last four characters of the line and we can do that
01:26with the dollar sign character, and again dollar sign character is a
01:31metacharacter and this one matches the end of the line.
01:33This time I put it outside of the parenthesis.
01:35You can put it inside or outside.
01:37These particular metacharacters, the beginning and ending of the line, they
01:40don't actually match a character so they won't return anything.
01:44They just match a position.
01:46So it can go inside or outside of the parenthesis. It really makes a little
01:49more sense outside.
01:51And I will go ahead and save and run that.
01:53And these are the last four characters of the lines that have four characters on them.
01:59Perhaps what you want to do is you want to get every match of a letter A that's
02:05followed by four characters, or followed by three characters in this case.
02:11And so we will get the A and the three characters after it.
02:13And we will save that and run it.
02:16And here we have the places where there's a letter A and four characters after,
02:23in this case it's a space character.
02:26And what we are finding here is that in fact there's some places where there is
02:30more than one match, where we are printing out $1 for each of them.
02:34And so we might want to get all of those matches on those lines and so in that
02:39case we can assign this to in an array.
02:41We can say list equals and we will put a g at the end of this so we are sure
02:47that we get all of the matches on that line.
02:50And then we'll message the join of that list.
02:52We'll say join with a colon, and the list.
02:58I will say if list.
03:02And so in this case, we need to put a line here so that works and we will
03:09save that and run it.
03:11And so now we have get all of these cases of an A followed by four characters
03:16and we get all of the occurrences of that on each line separated by colons
03:21line-by-line like that, and that gives us exactly what it is that we are looking for.
03:26Now this dot character can be repeated.
03:30We can specify exactly three of them by saying dot three like that and so we'll get
03:37occurrences of three just like we did before.
03:40That works exactly like it did before.
03:42We can use a large number here and not have to count them out.
03:46So putting a number inside of curly braces. That will repeat the match character
03:52before it that many times.
03:54And so we say save, run, and we get all of the ten characters with A. it's ten.
04:01All of the A plus nine character occurrences, and that works like that.
04:06Or we can use the asterisk, which means zero or more of these.
04:12And we will go ahead and terminate that with an S. so what this will give us
04:15will be all of the occurrences of an A and all the letters after that up to an S.
04:20So you will see that this does not do exactly what we expect it to do here.
04:26Go ahead and run this.
04:28And we will see that in some of these cases there's an S here.
04:31It ends in an S but it's the last S on the line and not the first S after the
04:37first A, and the reason for that is that the asterisk wildcard, which means
04:42repeat this as many times as you can, is what's called greedy.
04:46That means it will repeat all of them up until the last possible match after it.
04:52If you want it to be not greedy and to match up to the first possible match
04:55after it, you put a question mark after the asterisk and that makes the
04:59asterisk not greedy.
05:01So we'll save this and run it.
05:04And now we will get the shorter ones and a colon, and then the next one because
05:12we have this going into the list.
05:13So this is actually giving us the A up to the S, up to the first occurrence of
05:18the S, and then a colon because there's more than one match on a line and then
05:22the A up to the next occurrence of the S. So this is doing exactly what it is we want it to do.
05:27We have made the asterisks not greedy by putting a question mark after it.
05:32So these are some of the metacharacters.
05:34Again the regular expression language is extremely rich and you can get a lot
05:39of more out of it by looking at the documentation of the regular expressions
05:45that comes in the Perl.
05:46We have it here in this perlre.txt file or you can use the online documentation
05:51and look for perlre.
Collapse this transcript
Matching classes of characters
00:00Sometimes with regular expressions you are going to want to match a class of
00:03character, say all digits or all punctuation marks or something like that.
00:09There is a few different ways to do that in Perl.
00:12And so we are going to look at some of those.
00:14We will start making a working copy of regex.pl.
00:17We call this classes.pl and we'll open that and start by declaring an array,
00:29some place to put our matches.
00:31We will put equals, and it will be like that and we'll message out at the join
00:38of the list, if list.
00:44And we will probably use the larger file for this, perlre.txt, because we'll be
00:54looking things like digits and punctuation marks and there will be more
00:57examples of them in there.
00:58So we'll start by declaring a class for digits and we can do this in a
01:03few different ways.
01:04We can say 0 through 9.
01:06Classes, typically, in the square brackets like this.
01:10And we can declare a range of characters.
01:13So we can say something like 0 through 9, we can something like A through Z, or
01:18we can say A through Z, and capital A to Z, or we can use slash I for that.
01:25You can simply list things.
01:26You can say match all occurrences of 1, and 7, and 3 and these sorts of
01:32things work just fine.
01:33In this case, we will put a plus sign out there to say match one or more
01:37occurrence of this together.
01:39I'll put this in parenthesis and we'll go ahead and save it and run it.
01:48And there we have some examples here.
01:50We have 3 and 1 together, and we have a 7.
01:56This is just matching those characters.
01:58We want to match all the digits, of course.
02:00We can 0 through 9 and save that and run it.
02:05And we have got some examples with 0's in them and we have some longer
02:10numbers like 2029, 2028.
02:11Of course there is other simpler ways to match classes like digits, common
02:18classes like that, for example, the backslash d. We have seen that before in one
02:24of our other movies.
02:25That matches all digits.
02:27That's a shorthand for digits and we see that works exactly the same.
02:35Or we can use what are called Posix classes.
02:38And Posix classes are actually also enclosed in square brackets and so we
02:43need two sets of the square brackets, which Eclipse is giving us a little
02:49bit of hard time with.
02:51And the name of the class goes inside the pair of colons like this.
02:57And so if I say digit like that, this is using the Posix class for all digits,
03:05and so we save that and run it and then see that we get exactly the same result
03:11as we did with the other versions of this.
03:14So there is a number of different ways that we can specify classes.
03:19The Posix classes are named like this and they are all listed in the
03:22documentation. For example, we can say punct like that and that will get us all
03:27different types of punctuation.
03:29Save and run and there we have all the different types of punctuation
03:35listed there.
03:37There are backslash classes for a lot of things.
03:40There are things like any word characters with the \W like that.
03:47Word characters are any alphanumeric characters, letters, numbers or
03:53the underscore.
03:54You can match a non-word character with a capital version.
03:58So the capital versions are typically the inverse. For example, a capital D is
04:02anything that's not a digit.
04:05You can match white space with a lowercase w or anything that's not white
04:09spaced with a capital W. So there's a number of these as well.
04:14So these are the classes in Perl and these are how they are specified.
04:18Like I said there are a few different ways to do that.
04:21And the common ones, of course, the digits and the white space character and the
04:26alphanumeric characters we've looked at, there are a lot more of them and they
04:30are all listed in the documentation.
Collapse this transcript
Creating arrays with split
00:00There's one final way of using regular expressions that I'd like to cover here,
00:05and that is a Perl specific thing called split.
00:09It's a function that comes with Perl, and it's used for splitting strings apart
00:14on various boundaries and creating lists out of strings and this uses regular
00:19expressions and it's a little bit unique and I'd like to cover it now.
00:23So we'll start by making a working copy of a regex.pl file and will call it split.pl.
00:30Open that up, and we're not going to use the file here.
00:36Instead, we will create our time variable that we used before, and we will say
00:4305:27:32 and this time we are going to split it apart on the colons.
00:50We're going to do this entirely differently.
00:52We're going to say my ($hour, $minute, and $sec) = split and there's a regular
01:03expression match there and $time, and then we will message, hour:
01:08$hour, minute: $minute and sec: $sec, and we'll save that and run it.
01:24And you'll see that we got these elements and we didn't have to do it the way we
01:28did before with the matching the digits.
01:31Instead, we just match the colon with this very simple regular expression and we
01:35split the string on those boundaries into its three different parts.
01:40There's another wonderful example of how powerful this is.
01:45You'll notice that when we print out an error message, if we say here error,
01:53"this is an error message".
01:56Now we save that and run it. We get this long file path here and that's
02:06because that's actually the file name, the way that Perl sees it when it's
02:10passed into the program.
02:12So if we don't want all of that,
02:15we can split the string and say my @me= split and we can split it on the
02:22slash character.
02:25So we'll use the vertical bar here to match the slash character and comma $0.
02:34And for those we either are on Windows and you have backslashes instead, we can
02:37use a character class instead of that. We can say backslash which requires two
02:43backslashes because we're coding it and forward slash and the character class
02:48just like that and that works just fine, and then instead of this here we can
02:53print out $me and the last element of the Array which is indexed with a -1 like that.
03:02And so if we save this and run it, we see that we just get split.pl like
03:08that for the error message.
03:10Because we extracted all of the elements of that long path name and just took the last one.
03:17So split is very powerful.
03:18It's very useful, you'll see it is used a lot, and its syntax is very simple here.
03:23It just uses a regular expression to match what it's splitting on and the string
03:29itself and it returns a list of the elements after they're split apart.
Collapse this transcript
10. Subroutines
Understanding subroutines
00:00Subroutines are sometimes also called functions and they're a means
00:05of encapsulating code.
00:07There are a number reasons you might want to encapsulate your code in subroutines.
00:12Some of them are that Subroutines are reusable, so you can write a subroutine
00:17once and you can use it over and over within your program, or even put it in a
00:22library and use it within many different programs.
00:27Subroutines can be useful for hiding complexity.
00:31You want to keep your code clear, and so as complexity builds you put the
00:38complexity into different levels of subroutines.
00:40It allows your code to be clear and understandable.
00:45Subroutines can call other subroutines, and subroutines can even call themselves,
00:51something that's called Recursion.
00:53And this allows them to be extremely flexible.
00:58So let's go ahead and get into the details of using subroutines, sometimes
01:02called functions, in Perl.
Collapse this transcript
Defining and calling subroutines
00:00To begin our discussion of subroutines in Perl, we are going to talk about
00:04defining and calling subroutines.
00:07So let's start by making a copy of the subs.pl, and we'll call this one
00:14defining.pl, and we'll open that up, and we'll notice in here that the first
00:22thing we do is we call a subroutine, and this subroutine is main.
00:26And inside of main we call message, which is another subroutine.
00:30And this is an example really of reusable code and hiding complexity.
00:35I like to have a way to display messages that have a new line at the end of them.
00:41And so I'll create this.
00:43Pretty much in all of my command line programs I'll have something called message.
00:48And it will do what I want it to do to display a message.
00:52In this case it displays the message with a newline character at the end of it.
00:55This \n is a shortcut for a newline character.
01:00So that as I display messages, message one, message two, and
01:09message three,
01:13they're all on a separate line from each other.
01:15I'll go ahead and save that and run it and you can see what I mean.
01:19If I were to do this with print, I would have to put a new line at the end of
01:22each of these, and while that's not a terrible inconvenience,
01:25to me it's just simpler to do it this way.
01:28This is the subroutine that's being called sub message like that.
01:33A subroutine is declared, or defined by using the word sub and then the body of
01:40the subroutine is in a block, which is limited by these braces.
01:45And inside this subroutine you can get arguments and other details and we'll
01:50talk about these in later movies.
01:52Right now we're talking about defining and calling the subroutine.
01:56So it gets defined with the keyword sub and the name and the block.
02:00And then it's called by using the name of the subroutine followed by
02:05parentheses, and any arguments to the subroutine that you might have, in this
02:10case we have a string.
02:12Now if this subroutine were defined before the place where it's called, if
02:20it were defined up here, then in actuality you wouldn't even need these parentheses.
02:27You could call it like this.
02:35And sometimes you'll see it done this way.
02:37If I save this and run it, and in fact, with Perl's built-in functions, it's
02:45often common to have them called without parentheses.
02:52If you want to be able to call it that way, but you don't want to have to define
02:57it before the place where it's used, you can actually-- you see we've got
03:03errors here because now it's defined after and there's no parentheses here.
03:10You can declare it above by using the use subs.
03:16This is called a pragma.
03:19And use the qw operator, which allows you to use a list of words and creates a
03:26list from separate words, and you can put a message up here and a semicolon.
03:31And now, you can call that function without the parentheses.
03:39So we'll save and run, and you see there are no errors, and it works like we expected.
03:45You can even list several of them up here, error up here too, and you'll notice
03:50I have an error function down at the bottom. And then if I wanted to, I could
03:57make one of these an error instead.
03:59And save that and run it and you'll see that also can be called
04:07without parentheses.
04:08This is something that you'll see done now and then in other people's code and
04:12if you choose to do it, it's perfectly okay.
04:14I will often use message and error this way, so they can be called without the parentheses.
04:20Again, it's just another convenience, but it's one of those things that Perl
04:23allows that a lot of people use, that you'll see often.
04:26So that's how you define and call subroutines in Perl.
Collapse this transcript
Using arguments with subroutines
00:00When you want to pass data and variables and things to a subroutine it's called
00:07calling it with arguments.
00:08The variables that you pass to it are called arguments.
00:12So let's talk about how this is done in Perl and we will make a copy of the
00:17subs.pl and we'll call it arguments.pl.
00:21I will open that up and again looking at the message subroutine you'll see that
00:31this string is passed to it and throughout this course we've passed a number of
00:36different things to message.
00:39Inside of the subroutine we see this line here, which is how that argument is
00:44used inside of the subroutine itself.
00:48So the way this works is the arguments are placed inside the parentheses and
00:55technically in Perl this is a list.
00:58So you could, just to make this look a little bit simpler, my $s = and we'll just
01:04take this and move it up there, and then we will call it the $s. If you wanted
01:11to you could have several of them.
01:13You could have $y and $z and we could-- $y is a number and $z is another string.
01:27Then the subroutine is now being called with three arguments.
01:33So the arguments are in a list, which in Perl is in parentheses, and they are separated
01:38by each element of the list is separated by a comma.
01:42Those arguments are passed into the subroutine with a special variable, which is
01:49actually a list, and it looks like that.
01:54So if you wanted to get all of these arguments you could say my $m $y $z =
02:04this list, like that.
02:05We get rid of this one.
02:09Now you have all three of these. We're only printing one of them of course and
02:13print $m with the new line at the end of it.
02:17If we save this and run it it'll do exactly what we expect.
02:21We get just that first string which is in $s and we're not doing anything
02:26with the other ones.
02:28If we wanted to we could also display those, we could say display them in
02:32parentheses like this.
02:37We save that and run it.
02:39We see that we're actually getting all of those arguments, there they are
02:43out there at the end.
02:45So the arguments are getting passed in this array. An array is simply a variable
02:50that contains a list.
02:52They get pass to the function as the list inside of the parentheses and then
02:58inside the function you can use them just as you use any array or list, assigning
03:02them this way and printing them out that way.
Collapse this transcript
Understanding scope and "my" variables
00:00Subroutines in Perl are declared with a block and that block has the code that
00:06the subroutine executes when it's called.
00:09So just like with any block in Perl you need to be concerned with the scope of
00:14the variables that you use inside that block.
00:16So let's take a look at that.
00:18We will make a copy of subs.pl for our working space here and we'll call it
00:25scope.pl and we will open that up.
00:32One of the first things you'll notice is in our subroutine message, we have this
00:36variable here, $m, and it's declared with my.
00:39What that does is it keeps the scope of that variable inside of this block and
00:46this block of course is the body of the subroutine.
00:49This is actually very important.
00:52You want to make sure that the variables that you're using that you are
00:56declaring inside of your subroutine are local to that subroutine or owned by
01:00that subroutine, and cannot be accessed or modified from outside.
01:06There are ways to get around it, but you really don't want to.
01:10It's a lot cleaner to just make sure that your variables are your variables.
01:15For example if I were to have a $m outside of here and have it be some other
01:21string, I want to know that this $m inside of this subroutine is the one that
01:28I'm actually printing.
01:29So this is the one that's having the string passed from the function call there.
01:34So when I save it and run it, you'll see that is the $m that is being accessed.
01:42If I had a global variable, say something that's declared outside of the scope of
01:47any of these blocks, then it's certainly possible to reference that from inside.
01:51If I say have a $g out here and yet another string and I wanted to say print
02:01that every time I print something here.
02:03So I can say $g like that, and that $g is not defined inside of my block.
02:11So it's not local and so I am actually accessing the next one that's found in a
02:16scope that includes mine.
02:19So it goes up the tree of the scope and it finds the next $g. So if I save this
02:24and run it, you'll see that I get this yet another string and this here.
02:31So every time I print out another message, let's just print out this $m here.
02:38So this will be the some other string.
02:40It will put yet another string at the beginning of it.
02:42We hadn't run that and you see that we get that yet another string every time.
02:47So we can use that of course if we want to just have say the name of the program
02:51here, this is scope.pl, and you wanted to maybe identify that everything that
02:58gets printed out of here where it's coming from.
03:00You can do something like that and in that way you are using the scope as a
03:07tool and rather than having it just be an accident.
03:10So this is scope and this is how it affects functions, and this is how you use it.
03:16You want to make sure that your local variables are all scoped locally, and you
03:21want to make sure that when you are using variables outside of the scope that
03:25you do that intentionally.
Collapse this transcript
Returning values from a subroutine
00:00Often times when you are using a subroutine or a function, not only do you want
00:06to pass data into the subroutine but you also want to pass data back when the
00:11subroutine has done its job and this is called the return value and that's what
00:15we are going to talk about now.
00:16So let's go ahead and start by making a working copy of the subs.pl script and
00:22we'll call this return.pl, so we are going to learn about returning values.
00:30For this example we will go ahead and will write a new subroutine, something
00:36that let's just say just adds a couple of numbers.
00:38So we'll call this addnum, and we'll just pass it a couple of numbers here and
00:46our results will be in numbers.
00:48So I'll just say my num equals.
00:50Often times when I am writing something new, I'll start by saying how am I going to use this?
00:57And I'll write an example of how I am going to use it, and then I'll write the
01:00subroutine to match.
01:02So in this case, subroutine, we'll call it addnum.
01:06And in this case it takes two values, and so I am going to say my $v1 and $v2,
01:17equals like that, and so that will get me the two values that have been passed in.
01:23So these are arguments to the subroutine and this is how we read them in inside
01:29of the subroutine, by reading them from the @_ list.
01:34Then I will simply return the sum of these two numbers, $v1 + $v2.
01:41So return is a keyword in Perl and what it does is it takes its argument and it
01:48returns it from the subroutine so that the subroutine can then be used in an
01:55assignment context where that can be assigned to a number like this or you could
02:00use it as an argument to another subroutine.
02:03We'll print this one out, we'll just say $num like that, or we can say something
02:09like this, message addendum, and give it a couple of other numbers say 5 and 8.
02:18So when we run this we'll get two lines, one of them should be the sum of 2 and
02:234, which would be 6, and the other one would be the sum of 5 and 8, which would be 13.
02:28I will save that and run it, and there we have 6, we have a 13.
02:35So what we've got here is two different ways that we've called the subroutine.
02:39One is by assigning it to a variable and then printing out that variable.
02:44The other is by doing it directly without the intermediate variable.
02:48So we can see that the subroutine call syntactically it has the value of
02:55whatever you return.
02:57So you can call a subroutine in either of these ways or in any context where its
03:03value might be taken.
03:05The return keyword is how you declare what that return value would be.
03:12So what return takes is as its argument whatever the value is going to be that we're
03:16returning, and the subroutine can then be used in a context where that value is
03:23read and that is the value that will be used in that context.
Collapse this transcript
11. References and Data Structures
Understanding values and references
00:00In order to understand references, you need to understand the distinction
00:04between a variable that contains a reference and a variable that contains a value.
00:09A reference is a variable that refers to a value as opposed to a variable
00:14that contains a value.
00:16So, this is a variable as we understand them so far. The variable contains the
00:22value, whereas a reference variable contains a reference that refers to a value.
00:29This is probably best explained by example.
00:33In the Chapter 11 References folder in your exercise folders, go ahead and make
00:38a copy of refs.pl and we'll just call this example.pl. Open that up.
00:45Here we have a variable that contains a value.
00:49In this case, the value is a string.
00:52The string says, "This is the Perl 5 references chapter."
00:57Then we print out the variable using the message function.
01:01If we go ahead and run this, you'll see that it prints out this nice string.
01:06Now, a reference refers to the variable, so it uses this reference operator and
01:16then the variable itself.
01:19So now what we have is a variable called ref that refers to this variable here.
01:28So the value of this is the reference.
01:31If we print out ref, if we just say $ref here, what you'll is Perl's
01:36representation of the reference, which looks like that, scalar and an address.
01:42So this is referring to a scalar variable, because var is a one-dimensional
01:48scalar variable, whereas ref simply points to the value in that variable.
01:55So, I can actually look at the value of it by using another dollar sign.
02:00So what this first $, what that does is it says show me the scalar that is
02:06referred to by this reference.
02:08If I then save that and run it, then we get that value there.
02:16The advantage of this is that as I pass things around in my program and I
02:20make copies of them and I pass them into functions and return values and
02:26such, I don't have to pass around a whole lot of data. I can just pass around the reference.
02:30So if I make a copy of the reference, I now have another variable that contains
02:39the reference of same place.
02:40I can print out from that copy and I still get the same value.
02:46But all I've copied is the reference. I haven't copied all of these bytes.
02:49So let's say this is like a whole lot of data or some very complicated structure of data.
02:54I don't have to copy all of that.
02:56I can just copy the reference.
02:57I can pass the reference to a function or subroutine.
03:01I can do all kinds of things with it.
03:03In fact, if I print out the value of ref here and then I go down here and I
03:09change variable to something else, and then I message it again or message the
03:18copy of it. Now I haven't changed the reference. I haven't changed the copy.
03:22All I've changed is this variable. When I print it out the second time, we'll get the new value.
03:26So the first time, it prints out the string and the second time it prints out the number.
03:34So, references are extremely powerful and they are a little bit complicated,
03:39because you have to think in this indirect way about what's going on.
03:45But what the reference is, is just a pointer to the place where the data is,
03:51whereas the variable actually contains the data.
03:55So in this chapter, we're going to see some example of how references are used
04:00in a more powerful way, especially by using array references and hash references,
04:05which are the most common types of references, and then later on in the course,
04:10when we start talking about object oriented programming, you'll see that Perl's
04:15object model is built entirely on top of this concept of references.
04:20So where a variable contains a value, a reference points to a value.
Collapse this transcript
Defining array references
00:00References are not actually used very often for scalar variables. They are much
00:04more often used for arrays and hashes and combinations thereof.
00:09In this movie, we're going to talk about array references.
00:12I'll go ahead and will make a copy of refs.pl and will call it arrayref.pl.
00:18We'll go ahead and open that up.
00:25In this case, we're going to declare this as an array reference.
00:31So, array references are actually made with the square bracket.
00:49They can be all in one line or they can be moved across lines like that.
00:55All those red dots will go away when I save, here we go.
00:58In this case, we have it on multiple lines because oftentimes when you're
01:03declaring an array or a list or a reference to such, you've got so much of data
01:07that you don't want to put it all in one line.
01:09So it tends to be broken up across lines.
01:12I like to indent them like this so that I have some idea of what belongs to what.
01:17Now as we run this what we'll get is this result, which will say that it's
01:22an array reference.
01:24You'll see array and an address.
01:28What's with that is an address.
01:30So, when you print a reference, what you get is a representation of that
01:36reference so that you can see what the type is.
01:39In this case, we have an array reference.
01:42So we can use this array reference by just putting an @ in front of the $.
01:51So, for example, if we wanted to join this, we've seen how we can do this,
01:55join it with say colons, and we can use this just like we can any other list or array.
02:06Let me save that and run it.
02:08We'll see that we get all of these different values.
02:12The first one is "This is the Perl 5 references chapter" and then there is a
02:16colon, and then 42 and then another colon, and "Another String" and a colon
02:23and "one more value".
02:25So we have dereferenced.
02:27That's what this is called when you put the other symbol in front of the variable.
02:31We dereferenced it as an array or a list.
02:35Array and list mean the same thing in Perl.
02:37They are just two different words for the same thing.
02:40Then we used it in a join like we would with any other array or list and printed it out.
02:46So, that is how array references work in Perl.
02:51Again, this is really powerful, because if I want to make a copy of this, I can
02:55just say my $copy = $var, and I have copied the reference, but I haven't
03:04actually copied all the data.
03:06If I run this again with the copy here, I can save and run and there we have
03:12exactly the same result.
03:14In fact, if I wanted to change one of the values, I can change it through the dereference.
03:20I can do this like this.
03:21I can say copy and this is the way that you dereference a member of an array or
03:27hash with the arrow like that.
03:29Then I can subscript and I can say a number 2, which remember they are zero base.
03:35This is number 0, this is element number 1, and this is number 2 and I can assign
03:40it some other value like 187.
03:42Now, when I go and print it again, I'll just copy this line.
03:48Again, I'm working on the copy of the reference at this point, which is actually
03:54getting me all the way back here by dereferencing it.
03:57I go ahead and save that and run it.
04:00Then the first time it prints, it prints "Another String" as the third
04:04element there, right there.
04:07The second time it prints instead, it prints this 187, because we changed it.
04:13So, we did all that changing through the reference.
04:16We didn't have to go all the way back to the original variable.
04:21The original variable of course is a reference as well.
04:24The array itself in this case is anonymous, because I declared it this way with
04:30the square brackets.
04:31I could have, if I wanted to, done it this way.
04:37I can say this is a list and I can use regular old parentheses.
04:43Eclipse just makes that a little bit harder, just like that.
04:48Now I can say my var equals-- and I can reference that list, like that, and now
04:58everything will work exactly as it did before.
05:01Save this and run it and we have exactly the same result.
05:06So what we've done here is we declared a list in exactly the same way as we
05:09used to, using the list variable itself and using the parentheses like we
05:14normally do for a list.
05:16Then we have created a reference to it using the reference operator like we did
05:22in the last movie with a scalar.
05:24That reference operator works for any type of object in Perl and we created a
05:29reference and we called it var.
05:30We made a copy of the reference and we printed it out from the copy of the
05:35reference and we got all the way through to that original list, because there
05:39it is, printed out.
05:40Then we even went to and changed an element of the original list.
05:46And we got that result.
05:49So, this is how array references or list references work in Perl.
05:55Again, you use the reference operator to create the reference or instead you can
06:01declare it directly using the square brackets instead of the parentheses.
06:06You can copy it, because a reference is just another scalar.
06:10You can make a copy of it and it's just copying the reference.
06:13You can dereference it this way to get the entire array.
06:18You can dereference it this way to get an individual element of the array and
06:22you can even assign to it and change it.
06:26Then we print it out again and you get that changed value, because you've
06:31changed the original object and you're still referring to it with the same reference.
06:37So that's how array references work in Perl.
Collapse this transcript
Defining hash references
00:00One of the more common uses of references in Perl is for hash references.
00:05So we'll go ahead and take a look at how that is done.
00:09And we'll start by making a working copy of refs.pl. I'm going to call this
00:13hashref.pl, like that.
00:14And we'll open that up and we'll go ahead and declare a hash, and a hash is
00:24declared with the percent sign, remember, and parentheses.
00:30We have a few things in this, so we'll go ahead and give us some space to do
00:36these on separate lines.
00:37This is again a common way to declare a hash with multiple lines for the
00:42elements, and we'll say name and "Jimi Hendrix".
00:51It's very common when declaring hashes to omit the quotes in the key.
00:56And this is optional in Perl, and you'll see it done both ways.
01:00I tend to do it this way.
01:02Again, you'll see it both ways and is optional and you can just do whichever way
01:07seems more comfortable for you.
01:08But for this example we're going to do without the quotes for the key.
01:12Instrument is "Guitar", and lets say album, "Are you experienced?", and we
01:26can create a reference to that, like this here.
01:29\%hash and with that does is it takes the hash variable and it creates
01:39a reference, and assigns that reference to the scalar variable ref.
01:43So if down here I print ref, and we don't need this anymore.
01:50I'll save that and run it.
01:53We'll see that it prints hash and the address.
01:57So ref is a reference to the hash of that address, which is this hash here,
02:03which is named hash.
02:05And again this is even more common than to declare that way is to do it
02:10directly, and I'll call this hashref, and we'll use curly braces instead of
02:20the parentheses, and what that does is it creates what's called an anonymous hashref.
02:26So this here inside the curly braces is as an anonymous hashref, and it's
02:33assigned to this hashref variable, so that the way that you get it is through the hashref variable.
02:37And so we'll name this over here hashref, and we'll print it. We'll get pretty
02:42much the same thing probably with a different address.
02:45So it says hash, which is the type that the reference is pointing to, and the address there.
02:52And so that's our hashref.
02:54Again, we can make a copy of it if we want to and say copy equals hashref and
02:59the copy will look exactly the same.
03:03Save and run and if we want to we can operate on it, just like we normally
03:10would with a hash. We can say for each, my key, sort keys, and again we're going
03:18to refer to the hash.
03:21We can do it through the copy or through the hashref.
03:23And value equals $copy $k. So this is the dereference operator. We've seen this
03:37before with the array refs and in this case because it's a hashref, we've got
03:42the curly braces for dereferencing the hash.
03:45And so we're getting the value by using the key in the dereference and then we
03:53can message $k and $v like that, with semicolon and we save this and run it.
04:05Now this is a very very common use of a hashref and again, we can pass around
04:11the hashref itself. We can make copies of it.
04:14If I want to I can add an element and just say $copy and create a new key, say
04:21song equals and name it here, Purple Haze, and then when we print it out we'll see
04:30that we have yet another element in our hash. We have song in there. It comes out
04:36at the end, sorted after name, and we've done this through the copy. We didn't
04:40even do it directly through the hashref, because all of these point out exactly the same hash.
04:47And so you've actually added an element to the list by referencing it
04:52through the hashref.
04:54So this is very typical of how hashrefs are used.
04:58In fact, you'll often see them declared just like this, as an empty
05:07hashref and then things are added to them throughout the program, so that's also not uncommon.
05:15So this is a hashref. They're usually declared anonymously like this with the
05:20curly braces, although you can just create a hash and use the reference
05:25operator to get the reference and assign that to a reference variable.
05:29You can make copies of the reference, you can, pass around it, you can pass it
05:33to and from functions, you can add elements to it, you can manipulate elements
05:39in it, and you can use it just like you would a hash by dereferencing it,
05:45either with the percent sign, getting the entire hash or with the dereferencing
05:50operator to get individual elements using the curly braces.
05:55And that is how you use a hashref in Perl.
Collapse this transcript
Building mixed data structures
00:00A lot of the power of references in Perl is in the ability to mix-and-match
00:06different types of references all in one data structure.
00:10Let's take a look at what this means and how this works.
00:14We'll start by creating a working copy of refs.pl and we'll call this one
00:18mixed.pl, open that up.
00:22Now I'm going to go ahead and start with an array ref.
00:27I'm going to call this artists.
00:31And this is an array ref so I'll use the square brackets and we'll make some
00:36room to put some stuff in there.
00:39And we'll start with a hash ref.
00:42Now what we have here is an array ref, and it's reference to an array of hash refs.
00:51So there will be multiple hash refs in this array.
00:55Let's see in a moment how powerful this is.
00:58Say name and we'll use Jimi again, and his instrument is the guitar, and
01:05his genre is rock.
01:12And now we put a comma here because we're going to do another one.
01:16And rather than type all that again, I'm just going to use this structure and
01:22we'll go ahead and put somebody else in. How about Miles Davis?
01:25And his instrument is the trumpet and his genre jazz.
01:32We'll go ahead and put in another one, say Ella Fitzgerald, and hers is vocal
01:42and her genre is jazz.
01:43And you see what we end up with here.
01:49I will go ahead and maximize this.
01:51Is you have basically a list of artists, and yet it's a rich list.
01:57In each element you have multiple named elements.
02:01This is a very common structure.
02:03You'll see this used a lot.
02:04I am going to show you an example from our examples here in this course.
02:10If I want to take a look at this list, go ahead and print it out. We'll use a
02:17foreach loop, and we dereference it with the at sign, because it's a list.
02:27So, remember up here at the top, the list is called artists.
02:32Now we're using a dollar sign because a scaler contains the reference, but
02:38we want to dereference it and use it as the array.
02:42So we dereference it like that by putting the at sign in front of the dollar
02:46sign, and then it works just like any other array and we'll message.
02:51We're going to use a new technique. I'm going to dereference each of the
02:55elements separately all within the quotes.
02:58So artist is the actual hashref, because each element of this array is a hashref.
03:07So I dereferenced the individual element of the artist hashref with the
03:12dereference operator followed by the curly braces and I can say name like that,
03:17and say instrument, and genre, and it will just go ahead and it will print all
03:28of those elements out.
03:29So I'll save this and I'll run it.
03:32And there we have our list of artists in the order that we entered them.
03:39If I want to I can actually add another artist on the fly here.
03:43Use the push function, which pushes a new element on to an array.
03:47And the new element that we'll push on is actually going to be a hash ef.
03:54So we'll use an anonymous hashref here by just putting it in the curly braces,
03:58and I'll say name is say Yoyo Ma, instrument is the cello, genre is classical.
04:14And I can save that and run it and now we have four elements in the array.
04:22So in fact it's very common to declare an empty array ref and then just start
04:27pushing hash refs in with this sort of a construction here.
04:33We'll show you an example of that in our RandomQuote application.
04:39Go ahead and maximize this, and up here at the top you see I declare an empty array ref
04:49and it's called quotes.
04:51And then in the readQuotes, I call a function called newQuote and
05:01that's declared down here.
05:04And in newQuote, I push an anonymous hashref into the array that's pointed at
05:09by the array ref quotes.
05:11And then I returned the element that has that anonymous hashref.
05:18And so that gets used up here.
05:22Here's the newQuote call and so what we get here is the hashref that's been
05:27allocated in newQuote, and then I go ahead and I start putting things in it.
05:33So in effect building a structure like this, but I'm just building it on the fly.
05:41And it's incredibly convenient. You have to be able to visualize it.
05:47It takes a little bit of abstract thought to be able to see this, but once you
05:52see it and once you start using it, it's incredibly powerful and it allows you
05:57to do something like this application, which is a complete application that does
06:01everything that you need it to do and it works and we can run it here and it
06:06gives us random quotes every time we run it.
06:09You can build that in very few lines of code by using powerful tools like this.
06:14And this is I think one of Perl's most powerful paradigms, to be able to build
06:19these data structures on the fly like that.
06:21So that is the power of mixed data structures and references and that's really
06:30a lot of what references are good for in Perl.
Collapse this transcript
12. File I/O
Understanding streams and files
00:00When we talk about File I/O, it's important to understand two distinct types of files.
00:07You're probably used to looking at files as being those things are on my hard
00:13disk that I read from and write to, and they have date in them, or web pages, or
00:17documents or something like that.
00:19In fact, from the perspective of the computer program that you're writing, a lot
00:24of things are files.
00:25There are two basic different categories of files.
00:30One is the blocks of data that you used to thinking about.
00:33And these are like the files that are on your hard disk, and the other is
00:37something called Streams.
00:40A block of data is simply a chunk of a file that can be read or written to in one operation.
00:47A stream is data that may come as a series of bytes.
00:53This could be keystrokes from the user.
00:55This could be data sent over a network.
00:58It can be a lot of things.
00:59The point is that from the computer's perspective that's a different kind of a file,
01:04but the operations that you will perform in your code for how to read it
01:10and how to write it are substantially the same.
01:14There are differences in how files are read and written whether they are streams
01:18or whether they are blocks, but for the most part, the basic way that you deal
01:23with them are the same.
01:24This is an important key concept to understand as we go into talking about files
01:28for the rest of this course.
01:30So understand this, that files can be a lot of things.
01:34You're used to thinking of them as being files in a file system on a hard disk.
01:38Just keep in mind that a lot of different types of things are files, and that
01:42Perl like most of programming languages, especially those that have their roots
01:46in UNIX tend to deal with all these different types of things in the same way.
Collapse this transcript
Using file handles
00:00When you read or write to files in Perl, you tend to do this using
00:05something called a file handle, which is a different type of a variable in the Perl language.
00:11So we're going to look at file handles in this lesson.
00:14We'll start by making a working copy of files.pl, and we'll call this one handles.pl.
00:22We'll go ahead and open that up, and here you see we have a little bit of
00:26code that opens a file, and prints it out and closes the file, and so this
00:32uses the open function call.
00:34This variable here is a file handle. You'll notice that it has no dollar sign in
00:39front of it, or anything like that. It's not a scalar.
00:42It's not an array. It's a file handle.
00:44They tend to be written in all capital letters, when they are in this forum.
00:49And you'll see that it's using a couple of different places here throughout this
00:54little piece of code.
00:55And so the open function call uses a file handle as its first argument.
01:00Its second argument can be a file mode, or if you skip that it can just be the
01:06file name, so a little bit confusing, so I always include the file mode.
01:10It's just easier to remember that way.
01:12And in the event that the "open" is not successful, we have this "or" condition,
01:17and we'll print out an error.
01:19And in the error, this is important to notice, we have this $!, which will give
01:25us the error message from the operating system.
01:27So, the first thing we're going to do is we're going to make this error happen,
01:29because we're opening the file that does not exist in this directory, and
01:33you'll see the directory listing over here does not have workingfile.txt.
01:37We'll make that in a moment.
01:39And so this will fail and we'll get an error message.
01:42So we'll go ahead and we'll save this and we'll run it and we'll see we'll get
01:47the error message there.
01:48It says "cannot open file", because that's the message that I put here.
01:52And it has this $!, which gets interpolated and gives us the error message that
01:59says "No such file or directory".
02:01So that makes it really clear what's wrong as we don't have that file in our directory.
02:05So let's make a working copy of linesfile.txt here.
02:09And I'll call it workingfile.txt, and then when we run this code again,
02:16and there we go.
02:19We've got the five lines of text that are our working file. Open that up and
02:23you see it's got these five lines of text in it.
02:27And that's the result that we get.
02:30Here we're using the file handle to read from it and this is the simple form
02:36that's commonly used to read all the lines from a file, print while file handle.
02:41Putting the file handle in angle brackets like that in a list context, it will
02:46give you all of the lines of the file, or in a scalar context, it will give
02:50you one line at a time.
02:52So for example, I could write this the other way around and I could say while
02:59my $line equals file handle, so that's very clearly a scalar context.
03:06And I can say print $line like that.
03:10And if I save that and run it, it will give us exactly that same result that we just had there.
03:16The shortcut way to do it is the way that I had it before, which is simply print
03:22while file handle, like that, and a semicolon, and save and run, and we get that same result.
03:32This is commonly the way that you're doing it unless you have a lot more things
03:35to do in your loop than print.
03:37Another common thing to do with a file handle of course is to write to it.
03:42So let's write some quote that will create a new file and we're going to open
03:48another file. We'll call it new file handle.
03:52This one will be for writing. So we have the right angle bracket for writing;
03:56we have the left angle bracket for reading.
03:58You can look at it as reading from the file, because it's pointing away from the file.
04:03And in this one you can look at it as writing to the file, because it's
04:05pointing towards the file, and you can say newfile.txt, or error "cannot open
04:13file for write, so we know which one it is, with the bang, and we can
04:19call this one "for read".
04:22If we had our file names in variables, so we could put the filename in there
04:26instead, but this will work for now.
04:28And we want to make sure that we close it when we're all done.
04:30So we'll put a close down here, close NFH.
04:37Now we want to read from the old file and write to the new file.
04:41This will look like this.
04:42print new file handle while file handle, like that.
04:49And so it's just as simple as that. It looks like I'm missing a semicolon over
04:55here, and there we have it.
04:57When we save and run this, you'll notice we don't get anything to the console
05:02here, because we didn't print anything to the console.
05:06Instead, if we refresh our file system, and I'll just right-click on this in
05:10Eclipse and click on Refresh, you'll see we have a new file here. If we open that,
05:15it has exactly the same content as the workingfile.txt.
05:20So we have effectively copied one text file to another text file just by
05:26reading the lines in this while loop, and writing them to the new file.
05:30So, this is how you handle the standard, what I called the old-style
05:35file handles in Perl.
05:37For a simple operation like you're just copying from one file to another or
05:42you're just reading lines of text from one of the files and maybe doing some
05:46regular expressions on them or something like that, this will work fine.
05:50For a lot of others purposes, it's useful to use the modules that come with
05:55Perl for the object-oriented file interface, and we're going to look at that in
06:00our next lesson.
Collapse this transcript
Using the object-oriented interface for handling files
00:00The most common way to do File I/O in Perl is to use the object-oriented method,
00:06using the IO::File module.
00:08So let's take a look at how we do that in Perl.
00:12Go ahead and make a working copy of files.pl.
00:14We'll call this one oofiles.pl, object-oriented. We'll open that.
00:21In order to use the IO::File module, you have to first use the use statement to
00:26import the module into the Perl script.
00:31Then we can go down here and create our object.
00:34So, this is an object-oriented interface.
00:36So that means that we have to create an instance of an object.
00:41Objects in Perl are held in reference variables.
00:44So we say my $fh =, and then we call the object constructor from the module, and
00:51that looks like this, IO::File, and then the dereference operator and new.
01:00Inside the parentheses of the new function call, we put the name of the
01:05file, workingfile.txt, and the open mode, in this case a lowercase r for read-only mode.
01:14Then we can do the same or error, in this case, because I don't want it to go off
01:19the end of the screen, I'm just going to put the error call on the next line.
01:23I like to leave the OR hanging when I do this, so that it reminds me as I'm
01:26looking at it later that I've got something on the next line that's still
01:30part of this statement.
01:32Kind of hangs there instead of the semicolon to remind me.
01:36I'll put in here, cannot open file ($!).
01:41We can use exactly that same error message and the $!
01:45will expand to the operating system message.
01:48We'll see that in a moment, because we're going to run this before we actually
01:51create this workingfile.txt.
01:53Of course, I don't need that anymore.
01:55I actually don't need the close anymore.
01:58We'll talk about that in a moment.
01:59Instead of this FH here, we're going to use the $fh.
02:03In Perl, an IO::File object can be used exactly like a file handle and
02:09that's why I named it $fh.
02:12Close is not necessary here, because with the object-oriented interface,
02:16whenever this object variable goes out of scope, the object instance gets
02:21destroyed, which triggers the object's destructor method.
02:25In the destructor method for IO::File, the file actually gets closed.
02:30So the upshot of all of that is that when the File Handle variable, the object
02:37variable goes out of scope, the file is automatically closed.
02:41So, we don't have to do that manually. We don't have to remember to do that.
02:43If we forget to do it, obviously there is very little impact, because it
02:47happens automatically.
02:49So this structure here works exactly like it does with a regular Perl file handle.
02:54So we'll go ahead and we'll save this and we'll run it and we'll get our error
02:57messages first time there.
02:59There's the error message and this is getting expanded from the special $! variable.
03:06That is the operating system error message.
03:09Let's go ahead and make a copy of this linesfile.txt and we'll call this
03:14one workingfile.txt.
03:17Now that file exists, so if we run this again, we will get the output that we expect.
03:251, 2, 3, 4, 5, this is line 1, 2, 3, 4, 5, and that's from this workingfile.txt.
03:33So that's how you read a file using the IO::File object-oriented method.
03:39It's actually a little bit more common to do it this way.
03:41I'm going to show you this using the object-oriented interface from the file
03:46handle, rather than the default file handle operator here with the little angle brackets.
03:51That's a more common construct for the built-in file handles.
03:55When you're using the object-oriented method, it's more commonly done this other way,
03:59which I will show you right now.
04:01And that's using something like this, while my $line = $fh, and then the
04:10dereference operator to get at the object methods.
04:14In this case, we're going to use the getline method.
04:19We'll go ahead and put this in a block and we'll say print $line, like that.
04:26So this is a much more common way to do this with the object-oriented method,
04:30because you're using the methods of the object-oriented interface here, rather
04:35than the default file handle.
04:37This opens up all of the power of the methods inside of that object module.
04:43So I'll go ahead and save that and run it and we'll see that it does exactly the same thing.
04:48Yet in the long run, this is going to give us a lot more flexibility to do it this way.
04:52Now, let's take a look at how you would copy a file, so you can see file writing
04:57as well as file reading.
04:58I'm just going to make a copy of this constructor line and make the changes I
05:03need for opening a file for write.
05:06So I'm going to give it a different variable name for the object variable.
05:10And the file name here will be newfile.txt.
05:14Instead of read method, we're going to use the write method.
05:19Then we will differentiate our error messages, so we know which file is giving
05:23us an error, should we get one.
05:24I'll just say here for write, and we'll say over here for read, so that we know.
05:33Now we've opened a file for reading and we've opened another file for writing.
05:38Now when you open a file for writing, if the file doesn't exist, it gets
05:41created automatically. So that's good.
05:46Then down here all we need to do is change this one line.
05:51Instead of saying print $line like that, we're going to use the print method
05:56from the new file handle variable.
05:58So let's say $nfh and the dereference operator and then the print method.
06:05That's a method.
06:06it's a function inside of the object interface and we'll put this $line in
06:12parentheses, because that is not a built-in function call there.
06:17That's really all there is to it.
06:19We're now copying a file.
06:20So we'll go ahead and we'll save this and we'll run it.
06:25You see nothing comes in the output here, because it's going to file, so if I
06:28refresh over here in Eclipse's little file browser, we'll hit refresh there,
06:33we'll see there is the newfile.txt and it has all of the lines from the workingfile.txt.
06:41So that is how you use the IO:: File object-oriented interface.
06:46It's actually a lot easier to do and a lot easier to remember than the
06:51built-in file interface.
06:53It's a lot more flexible.
06:55In the long run, you'll find that there is a lot more that you can do with it.
06:58I recommend that you take a look at the documentation for IO::File.
07:03It's a little bit surprising when you bring it up here that there's not much in
07:08this particular documentation file at all.
07:12The reason for that is explained right up here at the top.
07:16IO::File inherits from IO::Handle and IO::Seekable.
07:20It extends these classes with methods that are specific to file handles.
07:25In other words, most of the documentation you're going to find in here, IO::Handle.
07:32So I'm going to press the Copy command on my keyboard and paste it up here so we
07:37can search for IO::Handle.
07:38When we bring up the documentation for IO::Handle, this is actually where
07:44you'll find most of the methods that are available in the object-oriented
07:48interface in IO::File.
07:50The reason for that is that there are many things that work like files.
07:55The socket interface for connecting to remote systems, the standard IO
08:00interface, a lot of different things work exactly the same and they all inherit
08:05this IO::Handle module.
08:07So this is where you will get the methods that you'll use for
08:11manipulating files.
08:14So, that is our IO::File example and you can see you create an IO::File object
08:21with the new method.
08:22The object is kept in a standard scalar variable and you specify the file name
08:29and the read or write mode, just like that.
08:32You can read line-by-line using getline, and you can write to a file using the
08:38print method with the file handle.
Collapse this transcript
Working with binary files
00:00Some operating systems draw a distinction between binary files and text files.
00:06It's important to understand how this works, especially if you're working with
00:10an operating system that has those distinctions where you expect your code to
00:14run on an operating system that has those distinctions.
00:18The most prominent operating system that has a distinction between binary files
00:23and text files is Microsoft Windows.
00:25In fact, all Microsoft Windows all the way back to MS-DOS have that distinction
00:30between text files and binary files.
00:32The upshot of this distinction means that with a text file the operating system
00:38will try to interpret and convert line endings.
00:42With a binary file, of course it will leave everything alone.
00:46If you try to read or write a binary file using the methods for a text file,
00:52it will try to convert the line endings.
00:56Your binary file will be corrupted.
00:58So we're going to show you an example of this and how to do it wrong and what
01:01happens and how to do it right.
01:04So what we have here is a binary file.
01:07It's a JPEG image and if we open this up, you'll see it's a picture of some olives.
01:11So, we'll go ahead and we'll make a working copy of files.pl and we will get to work on this.
01:19We'll call this binary.pl. Open that up.
01:23We're going to be using the IO::File module.
01:27So we'll go ahead and say use IO:: File and we're going to go ahead and make
01:32a copy of this file.
01:34So, we're not going to use any of this code. We'll go ahead and say the original
01:41file name is olives.jpg.
01:45The new file name, we'll just call it copy.jpg.
01:54We will open the original file using a file handle.
02:00This is an object reference variable, IO ::File->new, and we'll give it the file
02:07name and we will open it for read.
02:11We'll put out an error message if we can't open it.
02:24Now, I'm just going to make a copy of these two lines of code and just change
02:32the original file to the new file.
02:39I'm going to change read to write and come over here and change original to new.
02:46That should work just fine.
02:48Now we're going to copy the file.
02:49First thing we need to do is we need to create a buffer for the data.
02:52This is how you copy a binary file.
02:54In other examples, we've copied text files and now we are copying a binary file.
02:59So the method of doing this is a little bit different.
03:02I'm going to use the read method in the IO:: File object and that requires a buffer size.
03:10So we'll just create a variable up here for the buffer size.
03:14I'll call it bufsize and I'll make it a megabyte, so 1024 * 1024.
03:20Most computers these days can handle a megabyte buffer size in memory.
03:26So, we'll use a while loop and the read method from the original file handle.
03:35This is the file handle that we created up here for the original file where we opened that file.
03:40That's the olives.jpg.
03:42The method read will read a file using the buffer in the binary file mode.
03:49We give it the buffer as the first argument and the size as the second
03:56argument, like that.
03:59So for each buffer-ful, we're going to write the buffer, and we write the
04:03buffer, simply using the print method.
04:09This will read and write the binary file and this will work great on operating
04:13systems that do not have a distinction between binary files and text files.
04:18So if you're doing this on a Mac or if you're doing this on a UNIX system,
04:21this will work fine. We're on a PC.
04:23It's not going to work.
04:25So we'll go ahead and we'll save this and we'll run it.
04:30Just so we know when we're done, let's go ahead and put out a message when we're done.
04:33I like to know when I'm done.
04:35So nothing else is happening to the screen here, so I'll just put message
04:39"Done" at the end there, so we'll now save and run.
04:42We have the little message Done.
04:44So I'm going to refresh this because Eclipse doesn't refresh it.
04:48There is our copy and I'll go ahead and open that.
04:51It says "Windows Photo Viewer cannot open this picture, because the file appears
04:55to be damaged, corrupted or is too large."
04:58That's not a very specific error message, but we get the picture.
05:01The original file is fine, but the copy is not working.
05:05The reason for that is that the operating system tried to translate the new lines.
05:10It didn't realize that this was a binary file and Windows file system
05:16defaults to text files.
05:18So what we need to do is we need to tell it that it's a binary file and tell it not to do that.
05:22We need to do that in both the original file and the new file and we do this like this.
05:37What that does is it sets that file handle to binary mode.
05:43We'll do the same thing to the new file.
05:51We will save that and run it again.
05:53Now we have our Done message and we open up the copy, voila! It works.
06:00So that's the copy and that's the original and they are the same file.
06:05So, this is the important bit of code right here for working with binary files,
06:11even if you're running on a system that does not make this distinction.
06:15It doesn't hurt, it doesn't cost anything.
06:17It's always a good idea to go ahead and set your binary mode and use this string here, raw.
06:26Now, in Perl, if you call binary mode without any arguments at all, it will
06:30assume raw and it will go ahead and set it to raw.
06:33It's a good idea though for future compatibility, because you never know, to
06:38just go ahead and always put that string in there.
06:41So you'll see code a lot that just calls bin mode without any argument.
06:45You know that that's setting it to raw.
06:47But for your code, it's a really good idea to go ahead and include that.
06:51So just to recap here, we open the file in the same way we open it using the
06:57IO::File object-oriented.
07:00We set the bin mode on both the old file and the new file and we copy it using
07:08the read method and the print method.
07:11The read method takes as an argument the buffer and the buffer size.
07:15Of course, the print method will output whatever you give it.
07:19It outputs that to the new file handle.
07:21So we've got the new file handle for the write.
07:23We have the original file handle for the read.
07:27That is our copy code right there, to copy a binary file on any operating
07:33system, including an operating system like Microsoft Windows that draws a
07:39distinction between binary files and text files.
Collapse this transcript
13. Built-In Functions
Manipulating strings with built-in functions
00:00Perl has a number of built-in functions for dealing with strings.
00:04Let's take a look at some of them.
00:06We'll start by making a working copy of builtins.pl. We'll call this strings.pl.
00:11Go ahead and open that up and we'll start by declaring a string.
00:21And the first function I want to show you is one called chomp and what this does
00:26is it takes the new line off the end of the string, so we'll just put a new line here.
00:30A lot of times when you read a string out of a file, it will come with new lines
00:36attached to it which is normal and if it has that new line on it, you can use
00:42the print function and just say print $string and it'll print just fine.
00:47Save this and run it and you'll see it prints the string.
00:52If we were to print another line after it, let's say we print the string again,
00:55we'll see that the second string is on a separate line and that's because this
01:02new line is the end of it.
01:03If this new line wasn't here and we were to run that, you'll see that those
01:08strings were just run together.
01:10So the new line is useful and yet a lot of times, like for instance, if we were
01:15using the message function that we've been using throughout this course,
01:21it's more convenient not to have it or if you're processing your strings or putting
01:25them in array and joining them and doing different things, you might want to get rid
01:29of a new line that's already there.
01:31So if I have this new line here and let's say for example printing this in the
01:37middle of some other characters.
01:39Like for instance if I just put brackets around it for illustration purposes and
01:46put string in there, you'll see that when I save this and run it that, that
01:52that second bracket comes out on the next line and we might not want this to happen.
01:56So Perl has a built-in function for dealing with this and it's called chomp and
02:01what chomp does is it simply takes the new line off of the end of a string.
02:07We'll save that and run it.
02:09We see that now the new line is missing.
02:11If you try to chomp the end of a string that doesn't have a new line,
02:15it will leave it alone.
02:17So we'll do this again with a string that we already know has the new line
02:21missing and you'll see that it doesn't take anything else off of that.
02:25Chomp is an intelligent version of an older function called chop, which if we're
02:30going to use chop instead of chomp, it would go ahead and take yet another
02:34character off of the end of this and that is not what we want to have happen, so
02:38we use chomp instead of chop.
02:41There are some other interesting string functions that you might want to try
02:47and we'll declare a second variable here and we'll use that variable for printing out $s2.
02:56And let's say we wanted to get the uppercase of a string and use the uc
03:02function for uppercase.
03:04If we save that and run it, you'll see that the string is now all in uppercase.
03:09Or conversely, if we wanted to make it lowercase, you can use lc to make it
03:15lowercase and this is sometimes very useful.
03:19As long as we're talking about useful, one of the most useful functions that
03:23you'll find in Perl for dealing with strings is the substring function and there
03:28is actually a set of functions that work well together.
03:32Substring and the first argument is the string that you're going to be taking
03:38a subset of and then the second argument is where you'll start the substring
03:44and it's zero based.
03:45So if we wanted to just get these two letters here, we would count 0 for the T
03:50and 1 for the h, 2, 3, 4, so that would be 5 and 6.
03:55We would start at 5 and we would take 2 letters and that's the way this works.
04:00The first one is the starting place and the second one is the length of the
04:03substring and then s2 will just say is.
04:07We'll save that and run and we just have the letters is.
04:11And if we made this 4 letters long, we would get "is a" because we also get the
04:17space that counts as one, and we have "is a." So that's the substring function.
04:23If we want to find out where a string is within another string, we can use
04:29the index function.
04:31For example, if we wanted to find the first occurrence of the letter s in this
04:38string, we would just say this will find the first occurrence of the letter s.
04:45If we save this and run it, we see that the first occurrence is at index number
04:503 and again, counting from zero, 0, 1, 2, 3.
04:55If we wanted to find the last occurrence of the letter s, we would use rindex,
04:59which does the same thing as index, except it starts at the end and works
05:03backwards and so if I save and run, we'll see that that's at 10.
05:07So 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
05:14So that's the 10th one, counting from the left and starting at 0.
05:18And the beauty of this, they're all being zero-based together like this, is that
05:22we could actually stack them together.
05:24We could do something like this.
05:26Substring of $string starting at this place and then if you don't give substring
05:34another argument, it just goes to the end of the line and so here without
05:39actually sitting here and counting, we can say we just want the string starting
05:44at the last s and going to the end.
05:46So we'll get the word string and remember we have the rindex, which starts at
05:50the end and counts back and it finds the last occurrence of the letter s and
05:56using what that returns as the second argument to substring,
06:02the first argument being the string, then we're able to just get that part of the string.
06:07So if we save this and run it, we'll see that we get the word string.
06:12So those are some of the most common and powerful string functions available in Perl.
06:17There are a few others, so it's worth looking at the documentation for this.
06:22If we bring up the Perldoc and we search for perlfunc, func,
06:30that will give us a complete list of all of the built-in functions in Perl and they're categorized
06:38by individual functions.
06:40And then if we want to look one of them up, like for instance this one here,
06:44we can simply copy and paste into the search box there and we can get the
06:50documentation for that individual function.
06:53So those are the built-in functions for strings or the most common and
06:59powerful ones anyway and that's how they work in Perl.
Collapse this transcript
Working with numbers
00:00Perl has a small number of functions for dealing with numbers.
00:03Numbers are not really the strength of this programming language.
00:07This programming language was designed for dealing with text and it does
00:10that very, very well.
00:12While some scientific and mathematical applications have been written using Perl,
00:16they're typically done using libraries are not using the built-in functions.
00:20Perl has a limited number of functions for dealing with numbers and we'll look
00:24at some of those right now.
00:25We'll start by making a working copy of builtins.pl and call this one numbers.pl.
00:32I'll open that.
00:36One function that Perl has for dealing with numbers is to get the integer of a
00:40number, so we'll declare a number and we'll call it 123.456 and it's got a
00:47fractional part there.
00:49So we'll say my $n2 = int ($number) and we'll go ahead and print that, $n2, save
01:04and run and you see we have the integer part of the number.
01:09Perl has some functions for converting from other bases, like for instance
01:13converting from hexadecimal.
01:15If we had a number here that was represented as a string and that string was a
01:22hexadecimal number, say a5, then you can use the hex function to convert that
01:29into an integer and then display that and it will of course display in base 10.
01:33We'll save this and run it and there we have a5 in decimal.
01:40Likewise, if we have an octal number, we can convert from octal and of course,
01:46this is not a valid octal number but 75 would be a valid octal number and we
01:52save and run and there's that number converted to decimal.
01:57Perl also has a function for generating random numbers and it'll use your
02:01hardware's random number generator, if your hardware has one and we'll just get
02:07rid of this n2 variable for now and use the number variable and we'll say rand()
02:15and save that and run it and so this gives us a random number and you'll notice
02:22that this random number is less than 1.
02:25If you wanted to be scaled differently, you can put in a number here, say 100, and
02:31it will give you a random number scaled up to 100.
02:34I'll save and run and so we'll get 86.
02:37If we run it again, we get a different number.
02:41Run it again, we'll get a different number.
02:43So these are all under 100 and if you want of course just the integer part of that,
02:47you could wrap this random function in an integer function and get just
02:52the integer part of that, there's 10, 17, so these are all integers under 100.
03:01You can also seed your random number generator by using srand and that allows
03:07you to give it a seed and what this does is it gives the random number
03:10generator a starting place.
03:12So if you seed it with a constant number, it will always give you the
03:16same random number.
03:17For instance, if we seed it with say 125 and save that and run it then that
03:24random number comes up as 2 every time.
03:27So sometimes what I'll do is I'll seed it with some combination of the process
03:32ID plus the time and maybe something else and then every time I run it,
03:40I'm guaranteed to get a different number and there we have that.
03:46So those are some of the number functions that Perl supports.
03:49There are a few more.
03:50There are a limited number of mathematical functions like cosines and tangents
03:54and things like that.
03:56You can find those in the documentation.
03:59If you run Perldoc and type in perlfunc, you get a complete list of the
04:08built-in functions that are available in Perl and they are categorized down
04:13here and there's the list of numeric functions and you can look them up
04:19individually in Perldoc.
Collapse this transcript
Manipulating lists and arrays with built-in functions
00:00Perl has a number of functions for dealing with arrays, and we'll take a look
00:04at those, right now.
00:06Arrays and Lists are really just two different names for the same thing.
00:10More often than not the term, List is applied to the literal lists, and the term
00:16Array is applied to the Variables.
00:18We'll make a working copy of the builtins.pl here, and we'll call it arrays.pl. Open that up.
00:26We'll start by showing you a nice function that's a great shortcut for defining an array.
00:32We'll say my @list = qw and parentheses, you can think of it is standing for code word.
00:42What it does is it lets you put a bunch of literal words in parentheses or
00:46really any delimiter, the parenthesis are used commonly.
00:50Those words are then put into an array if they were strings.
00:54For example, I can just say Jan, Feb, March, April, May, June, July, August,
01:03September, October, November and December.
01:07I think that's all of them.
01:10This will create an array that will have all of those strings in it, so we go
01:16ahead and print the join of that.
01:18Join is another wonderful function for dealing with arrays.
01:25What join does is it takes two arguments.
01:27The first argument is a delimiter and the second argument is the array itself.
01:31Then it will take each of the elements of that array and join them together
01:34with that delimiter.
01:35That will allow us to print this out in a way that we can see it.
01:40So, we'll save this and run it.
01:42There's all of our strings delimited by these colons here.
01:48So, that's a great way to define a list using the qw operator.
01:54Let's say we wanted to add something to the end of the list.
01:56Let's say we made up a new month, and we call it Foo.
02:00So we can use the push function for adding something to the end of a list.
02:06So, push will just push that on to the bottom of the list.
02:10If I save this and run it, you'll see we have a new month here called Foo.
02:15Likewise, if we wanted to pop one off the bottom, push and pop to the opposite things.
02:20So, if I say my $string = pop and the name of the list.
02:27Now, a lot of times with built-in functions people don't put the parentheses
02:32because they are built-in, Perl is able to use them like this.
02:35So, you can type this with or without the parentheses.
02:38If I would type it with the parentheses, it will work exactly the same.
02:41But pop is one of those ones that all often just write this way.
02:46So, now I have this string, which will be the last element of the list, so I am
02:49going to massage that one separately.
02:51Then we'll go ahead and save that and run it, and you'll see that I have
02:55December up here, because I messaged it separately.
02:59That's the string that I popped off the list.
03:02December is not over here.
03:03it actually took it off of the list and returned it to me, so I could have it in a string.
03:08So, that can be really convenient for keeping a stack of variables.
03:12You can push on and pop them off.
03:13They come often the reverse order that you put them on and that can be really
03:17convenient some times.
03:19You can do the same thing at the top of a list with shift instead.
03:24So if I say shift instead of pop, it will take January instead of December. We'll run that.
03:30There we have January, and January is not on the list.
03:35Likewise, if we wanted to, we can unshift and put it back.
03:47We'll go ahead and message the join of the list again, so we can see that it went back.
03:57So, here we have shifted it off to the top of the list and we printing it out.
04:03We print the list without it.
04:04Then unshift puts it back on and it will print the list again.
04:07So, we should get January, and then this list like this.
04:10Then we should get the whole list, all put back together afterwards.
04:14Sure enough there we have it.
04:15There is January back where it belongs.
04:18Finally, let's just go ahead and take some of this stuff out here.
04:26There we have our list, just save that and run it, ensure that here we have our
04:30complete list there.
04:32If we want to print the list in reverse order, we can say reverse.
04:35What reverse does, reverses the function that will actually return a copy of the
04:39list in reverse order.
04:41So, there will now be a copy of the list there.
04:44Let's save that and run it.
04:46In fact, if we wanted to instead, we could say rlist = reverse of @list.
04:55Then we could print list and we could print rlist and see both of them.
05:02Save that and run it.
05:03You have the list in forward order, and the list in reverse order.
05:07Or if we wanted to, we could make a sorted list by using the sort function.
05:12We'll print this out as slist there. save and run.
05:18Now, we have a list that's in alphabetical order.
05:22That can be useful for a lot of things that are not months of the year.
05:26So, those are the list functions.
05:27You can see that there is a good assortment of them, pretty much everything that
05:31you will need for dealing with lists in Perl.
Collapse this transcript
Retrieving and formatting time
00:00Perl has a few functions for dealing with time, mostly for finding out what the
00:05date and the time is and for handling those variables.
00:09So let's take a look at how those work here in Perl.
00:13We'll start by making a working copy of builtins.pl.
00:16We'll call this one time.pl, and we'll go ahead and open that up.
00:22First we'll just go ahead and get the time and we'll create a variable called
00:26t = time, and time is a built-in function. I don't actually need the parentheses.
00:33That will go ahead and give me the current date and time, and what it gives me
00:39is you'll see it's just a number and what this is, we'll save that and run it,
00:45this is the number of seconds since midnight on January 1, 1970.
00:50That's called the epoch and that's the epoch used in most modern operating systems.
00:56There are some operating systems notably older Macintosh before OS X that use
01:02a different epoch.
01:05So most of the time what you'll see when you use this function is you'll
01:09see that number of seconds it's January 1, 1970. Sometimes you may see something else.
01:16But never fear, there is a way to get the time out of this.
01:19And so we go ahead and say my now =, and I'll say localtime of t, and that will
01:29give me a variable that will tell me what the date and time is here and now.
01:34I'll put that out and save that and run it.
01:37And here we have this strangely formatted Friday, March 12, at this date and the year.
01:44It's got the year over here.
01:45That's actually a standard UNIX-ism and of course Perl's legacy is in UNIX and
01:52so this is the kind of a date and time
01:54that's often used in e-mail messages and things like that.
01:57This is just the way that somebody formatted it one day and it stuck.
02:01And so if we want it in a different format.
02:04We can take a look at the manual page for local time, go ahead and bring that up,
02:10and you'll see here that in a scalar context it gives us that string that we
02:18saw but in a list context it gives us this array of variables.
02:26So I'm going to go ahead and I'm going to press Command+C on my Mac or Ctrl+C
02:31on a PC or whatever.
02:33It will copy that into the Copy Buffer, and I'm going to paste that in here,
02:41like that, and now I have all of these variables.
02:45So I can print a string with some of the stuff in it.
02:50For example, let's say I want the year and the month and the day.
02:58I'm going to use the mday variable, which is this one here which is the day of the month.
03:06This is not actually going to give us the result that we expect.
03:09That would be too easy.
03:11Go ahead and save this and run and show you what we get.
03:14A couple of things here that just look wrong. The year is not 110, and the month
03:18I happened to know is March, as we saw in the last screen if you were
03:23paying attention, and this says that the month is 2.
03:26Now there are reasons for this but the bottom-line is that the year is the
03:32number of years since 1900.
03:34So I have to add 1900 to the year.
03:37So I'll use this little shorthand notation, say += 1900, and that will give me
03:42the year that I'm expecting.
03:43So I'll save and run and 2010 is the correct year.
03:47The month on the other hand is this way on purpose, and this is 2 because it's zero-based.
03:54So this is really convenient if I want to print out the actual name of the month.
04:00I can make an array, call it months, and put in here Jan Feb Mar Apr Jun Jul Aug Sep Oct Nov and Dec.
04:18And then over here where we're printing out the month instead of doing like that,
04:22I need a space here, I can say months sub-month like that.
04:32That will index this array and it will print out the name of the month.
04:38So the month is March and the day is 12.
04:41So that's actually really kind of convenient.
04:44So if I wanted to here, I could print this out year and put a -month and put a -day
04:55and I can get the time, if I want here, I can say $hour, $min and $sec, and
05:06print that out, and there we have it.
05:09The second doesn't have a 0 in it and we could do some formatting to get that correct.
05:14In a nutshell though, that is how you get the time and the date using the
05:19local time function.
05:20Likewise if you want to, you can, instead of local time, you can get Universal
05:25Time or Greenwich Mean Time.
05:27You just say gmtime here instead of local time and save that and run it and
05:33that gives us the time in Greenwich Mean Time instead.
05:37So those are the time functions that Perl provides and that's how they work.
Collapse this transcript
14. Modules
Leveraging code with modules
00:00Modules are collections of Perl code for use with different scripts.
00:05So what that means is that this is how you reuse code in Perl.
00:11Modules can be a set of functions that you've written, big pieces of data that
00:16you've written, or you can get them from other places like the Comprehensive Perl
00:22Archive Network or CPAN, which is a repository for modules that have been
00:28written by all kinds of people all over the world,
00:31I even have some module up there, which you can download and install on your
00:36system and use them with your code.
00:39So modules are really a great way to leverage code that you've already written
00:44and to leverage code that others have already written, so that your effort can
00:50be maximized in writing your own code using these modules.
00:55Modules can be object oriented or they can be procedural.
00:59Most modules are object-oriented these days but there are still some
01:03modules that use procedural techniques and there are some modules that can
01:07be used either way.
01:09And modules can of course contain code and/or data and sometimes we don't
01:15think of reusing data.
01:17But for example, I've got a module on CPAN, which is simply a list of address
01:22codes with country codes and state codes, with both the two letter codes and
01:27the names, so that you can use it in creating lists on websites and things like that.
01:32So reusable code and reusable data is something you can do with modules.
Collapse this transcript
Understanding object-oriented and procedural modules
00:00Perl modules can be either object-oriented or procedural or in some cases, they can be both.
00:06Most modules today are object-oriented.
00:09Object-oriented code has these properties.
00:13Object-oriented code is dynamic.
00:16That means that the object determines what code to invoke, not the caller.
00:21So if I'm using an object-oriented module and I call a particular method inside
00:26that module, the object depending on how I'm calling it and in what context,
00:31what's been inherited and things like that, will decide what code to run
00:36inside that module.
00:38Encapsulation is another important property of object-oriented code and that
00:43means that the object contains all the code and all the data that it needs and
00:47I don't have to worry about providing that.
00:50The details of how things are done or hidden from the user, the user being the
00:56programmer, the one whose using the module.
00:58This is what's called abstraction and that's also an important property of
01:03object-oriented code.
01:05And finally, one object may inherit the properties of another object, in fact it
01:10can even inherit code, and this makes it easier to write object-oriented code.
01:16Once you already have a basis
01:19in other modules you can inherit the code from those other modules and the data
01:24and use that in your code without having to write it over again.
01:28On the other hand, procedural code has these important properties.
01:32Sometimes it's a lot simpler to write procedural code.
01:36Small subroutines may be coded quickly and easily.
01:40Procedural code may be very modular, functionalities may be used and
01:45reused, much like they can be in object-oriented code but with the
01:48simplicity of the procedural.
01:50And procedural code tends to be more linear and sometimes more clear and more readable.
01:56So these are reasons why you might want to write your modules in object-oriented
02:00fashion or in a procedural fashion.
02:02And like I said, most modules are object-oriented these days.
02:06Object-oriented programming is very popular.
02:09Most of my modules are object-oriented because of the inheritance property makes
02:13it really easy to use for more complex tasks, but for very simple tasks, often
02:19times a procedural approach is the approach that's going to make the more sense.
Collapse this transcript
Creating modules
00:00So you have a piece of code that you'd like to reuse and you want to put it into a module.
00:05Let's take a look at how you do that in Perl.
00:07We'll make a working copy of modules. pl here and we'll call this creating.pl.
00:15So we're going to create a module and there it is. Open up the window here a little bit.
00:22I'm going to paste in a piece of code here. If you want to do the same thing,
00:27you can find this code in the Example- finished.pm file in your Exercise Files.
00:33Or you can just pause the movie and type-in what you see here.
00:36So we'll start by creating a new file.
00:40I'm just going to right-click on this folder here and let's say New > Perl
00:43File, and we will name this example.pm.
00:48Modules in Perl are usually named with a .pm at the end and they are also
00:53usually named with capital letter at the beginning.
00:57That's very common.
00:58Sometimes it's something with initials like DB, you might name it DB with
01:03both capital letters.
01:03But the first letter is usually a capital at least.
01:07So we'll call this Example.pm.
01:09We'll put it in that file there and we will start by putting in a comment
01:14here and we'll call this example.pm and you can put what it does, Example
01:21perl module, and who wrote it and whatver else you want to put in your comments there.
01:27Then the first line in the file should be the package name, and in this case
01:32we're going to say package Example.
01:36Most of the time that is going to be the name of the module and that's going to
01:40be the same as the name of the file without the file extension.
01:44So the package name, what that does is that sets up the namespace.
01:48The way that modules work in Perl is they work on top of Perl's namespace
01:53model, so each module has its own namespace and the package keyword is how you
01:59set up the namespace.
02:00We're always going to use strict and use warnings and we're always going to put
02:07in a version string.
02:09And you'll use our for that instead of my and this makes it public so that the
02:16calling program can reach into this module and check the version to make sure
02:21that it has a version that it needs.
02:23And this is used throughout Perl's system for keeping track of modules, so you
02:29want to have a version number and in this case I'm going to name it 0.1 and
02:34you do put it in quotes like that and that allows you to use different types
02:37of naming conventions.
02:39So the next thing you need is you need a constructor because it's going to be an
02:44object-oriented module, as most modules are.
02:48So the constructor is usually named new.
02:50It doesn't have to be but it's convention so we are going to create a
02:53sub-routine, a function called new, and that's going to be the constructor for
02:59the object-oriented module.
03:01And this is very simple.
03:03It basically has the class name and that gets passed in, in the way that it's implied.
03:12You don't actually pass it in explicitly and you'll see how that works when we
03:15use it from the calling side. And there is always a self and what this is,
03:22this is an anonymous hash and most modules. Again, this is not something that's
03:27required but most modules use an anonymous hash for its instance data.
03:33And if you're familiar with object- oriented programming, instance data is the
03:36dynamic data that goes along with each invoked instance of a class but is
03:42different is in the name space of the classes it's running.
03:45It's not static; it's dynamic.
03:48And then we're going to use the bless function to turn this hash into an object,
03:56and that looks like this, and finally the constructor returns a reference to the
04:04blessed class, and we now have an object.
04:11Finally, and this is a Perl convention, the module must end.
04:17It must return 1 and that is traditionally done by just putting a 1 on a line by
04:23itself with a semicolon, and we now have a working object-oriented model.
04:30Well, it doesn't do anything yet.
04:32We'll go ahead and we'll save it and we will continue and we'll take this code
04:37here and we will copy this.
04:41We don't need the message done, pressing the copy key, Command+C on a Mac or
04:46Ctrl+C on a PC, and I'm going to paste it over here and then we'll turn this
04:56into an object method, so we'll say copyfile.
05:01That's what we'll call it and put the closing ridge down here at the end and
05:07then we need to make this into the calling conventions for a module.
05:14Now in object-oriented Perl, the first argument is always a reference to the
05:20object itself and then we have the original file name and the new file name
05:28and equals = @_. So that's how arguments are passed in Perl and so we don't
05:35need these two lines.
05:37The buffer size we're going to want to keep and we need a my here and this can
05:46stay the same but we need to import the IO file.
05:48So we'll go up here to the top and we'll say use IO::file like that and
05:54scrolling back down.
05:55We're saving the binmode, we're copying the file, and when we're done we're just
06:04going to return a 1 for true that we are successful.
06:10Finally, these error calls here, we don't have access to an error function from
06:15within the module so we're going to use Perl's built-in error function called
06:19die and what that does is it does a hard exit with an error message.
06:24And it will give you a stack trace and tell you what line it was called on and such.
06:30And just in the case that it can't open those files.
06:33So there we go, we have a rudimentary object method in our module.
06:39We'll go ahead and we'll save this and we'll come over to the creating side.
06:43Now we don't need all of this anymore, and instead what we can do is we can use
06:50the module up here at the top.
06:52We'll say use Example and that's all we need to do there.
06:59And here we say my object = Example-> new and then we can say object->copyfile
07:10and you see that Eclipse already knows about it because we have it in that same
07:14directory there and we give it the two file names.
07:18So the first file name is olives.jpg and the second file name is newfile.jpg
07:28and a semicolon here.
07:30What happens here is a couple of things, let's just talk about how this works.
07:34When I construct the new object with this example and the dereference operator
07:40and new, what gets passed is the word example.
07:46So that the object knows the name of its new object, and this gets shifted
07:52into class and so the built-in bless function blesses the self, which is this
07:58anonymous hash with the name of the object which gets passed in from this constructor call.
08:04Once we have created the object and we now have this object reference in a
08:08variable that object reference then gets dereferenced and the method gets
08:13called which is copyfile.
08:15And you'll notice we have two arguments here but actually three arguments
08:19show up on the other side because self always gets passed.
08:24And that is actually a reference to this anonymous hash that's constructed and
08:29that's how it carries along its instance data.
08:32So we'll go ahead and we'll save this and we will run it and we have the Done here.
08:38It looks like it worked.
08:39We'll refresh this directory and we see that we have a copy of the file.
08:45Double-click on it and there it is. That's a copy.
08:47So this jpeg got copied, here is the original and the copy, and all we had to do is this.
08:54Anytime we need to copy a binary file, all we have to do is bring in this module
08:59and invoke the copy function and we're done.
09:03So that's how you reuse code by creating a module in Perl.
09:09It's really a very simple process.
09:11It seems like it has a lot of steps.
09:13But the easy thing to do is to keep a template around and here I have a
09:17template called template.pm.
09:19This is included in your Exercise Files and this is a template.
09:23It's got the constructor there.
09:25It has a little sample method and it even has pod documentation, which we'll
09:30talk about in another chapter.
09:32So you can use this as a starting place, just change the name here, change the
09:36name there, and put in your own code and you're done.
09:40And you have a working module just like we created here from scratch.
09:45So that's how you reuse code by creating a module in Perl.
Collapse this transcript
Understanding object and instance data
00:00As you're creating your modules, it's important to understand the distinction
00:05between object data and instance data.
00:08So let's look at an example so that we can understand that.
00:11We are going to start by making a working copy of the Template.pm, and we'll
00:16use this to create a module, an object oriented module called Artist.pm.
00:21Go ahead and open that up.
00:24I will start by changing the name here and changing the name here.
00:32The module will not work if you don't change the name in this place right there,
00:35so that's really important.
00:39So this is actually an example of object data.
00:43This data here doesn't change from instance to instance and it's actually
00:47stored in the module.
00:48It's not stored in the object variable.
00:51I am going to go ahead and take this method here and we are going to call it
00:56Name and we are going to use this as what's called a setter-getter where we
01:00actually set instance data and get instance data in the same method.
01:06We are going to pass a variable in that is name and it's typically the same name
01:13as the setter-getter.
01:14The setter-getter is named the same name as the instance data and then we are
01:18going to create an instance variable in Perl that looks like this.
01:24So that's an instance variable.
01:26It's getting stored in the hash that's pointed out by self.
01:30So you remember up here in the constructor you created an anonymous hash and you put
01:36it into self, self is a hash reference and then you blessed that hash reference
01:41and it became an object reference and it got returned.
01:44So every time you create an object you create an object reference and it uses
01:50this anonymous hash and then all of the data that you create that's instance
01:54data like this gets stored in that hash and gets carried around with that
01:58particular instance of your object.
02:01You have different instances on an object. You can have different data in them.
02:04We will see how that's done here.
02:06So this will get name, which is getting passed in here, and I am just going to
02:11put if defined $name.
02:14I am going to put the dollar sign in there.
02:17That way it doesn't get called if you don't pass name, and then we're going
02:21to return the instance data, and that way this can be used as both a setter and a getter.
02:27So if you call this method with an argument, that argument will get used to set
02:32the instance data. If you do not pass in an argument,
02:36then you'll simply be getting a copy of the instance data.
02:40Let's see how that works.
02:42I am going to save this and we are going to make a working copy of modules.pl
02:46where we will call it and we will just call this oodata.pl.
02:51We are going to use this module, use Artist, and we are going to create an
03:00instance of the object $o = Artist->new, and then we will set the instance data
03:10$o->name and we will name this artist Jimi Hendrix, and then when we want to get
03:21the object data, we can put in a variable if we want to or we can just get it
03:25directly in the message call here.
03:27That will print out the name Jimi Hendrix.
03:31So we will go ahead and save this.
03:34What we're doing is we're creating an instance of the object and that instance
03:38gets saved in this object reference variable here and then we're using the
03:43method in this object to set the instance data to Jimi Hendrix and we're
03:49retrieving that instance data by calling the same method.
03:54When we run this, we'll see it prints out the name Jimi Hendrix.
03:57Now if I wanted to I could create a different artist, my $o2 = Artist->new, and
04:06we can give that one a different name, say Miles Davis. This is o2 and if I
04:14were to call o2 name here instead of the original O, then we will get the name Miles Davis.
04:22That's instance data you can see because that data is actually getting stored in
04:26the object reference, the instance of the object.
04:29If I want to just get the object data, remember this has object data as well
04:33in the form of this VERSION, and you can clear all kinds of variables here if you want to.
04:38It's not a good idea to overuse this because it's persistent.
04:42I can just message, if I want to see what version I have got, I can just
04:47say message Artist
04:48VERSION like that and give it a dollar sign because it's a scalar.
04:54And when I save this and run it, we see we get the version number down here.
05:00That also gets carried along in each of the instances.
05:03So if I say $o2->VERSION like this, I will still get that object data.
05:08But that's the static object data.
05:10That's not dynamic data.
05:12That doesn't change.
05:13If I were to change it, it would change for all the instances.
05:16It's not carried along in each individual instance and do not change it.
05:20It's a really bad idea to use object data like that.
05:24It gets very confusing very quickly.
05:27So that's the distinction between object data and instance data.
05:30It's important to understand and it's important to keep track of it as you
05:34create modules using the object-oriented model.
Collapse this transcript
Installing modules from CPAN on Mac and Unix
00:00CPAN is the Comprehensive Perl Archive Network.
00:05It is a repository of many, many modules that have been written by many,
00:09many different people.
00:11As such these modules vary in quality. Some of them are wonderful and bug
00:16free and used a lot and some of them are not.
00:20So this is where you would search for something that works with JPEG files
00:26and you'll get a long list of modules that may or may not do what is it that
00:32you want them to do.
00:34Once you have identified the module that you're looking for and you want
00:38to install it, the easy way to install it is by using the CPAN command line application.
00:45If you're on a Macintosh or a UNIX system, you'll do this from the command line
00:50and you'll type in something like sudo cpan and the name of the module.
00:56You're using sudo here because sudo allows you to run as the root user, because
01:02you will be installing the module system wide for the entire system.
01:07It is possible to install from CPAN for an individual user, but how you do that
01:13is going to differ from system to system.
01:16So what I'm going to show you here is what works and the way that it is normally
01:21done which is to install it as root.
01:25So I'm going to go ahead and install a module. I'm going to install one of my modules.
01:30This one is called BW::Base.
01:33What it is, it's the base of the module system that I've written.
01:37It installs a lot of utilities that are useful and that are used in a lot of the
01:42programs that I write and that I distribute.
01:45So that's all that's involved.
01:46You just type sudo and cpan and the name of the module.
01:50I'll press Return here and it will ask for the password because sudo asks for
01:56the password. Type that in, and there we go.
01:59If has fetched it from CPAN and it has installed it.
02:03Now there's all kinds of messages here.
02:05Some of them may look like errors, sometimes it'll come up with errors and it
02:09will go around them.
02:10It'll have trouble downloading from one place.
02:12It'll try some place else.
02:13You'll often get this one right here.
02:16What you're looking for is this line, /usr/bin/make install -- OK.
02:21If you see that then it went fine, if you see something else then there may be a problem.
02:27It may be missing something.
02:28It may need some dependency modules installed.
02:31It'll tell you what to do but this is what's involved in installing modules.
02:36Now CPAN is not perfect.
02:39The CPAN utility that installs the modules is not perfect.
02:42It often comes up with errors.
02:44It can be very confusing and very difficult and often times even I will go
02:50around using CPAN and just download the module and install it myself.
02:55So I'm going to show you briefly how to do that as well.
02:58So I'm going to go back to the web browser here and I'm going to go and find
03:02one of my other modules, which is called BW ::DB, and we will install that the other way.
03:07So I'm going to click on it here.
03:10I'm going to download it, where it says Download.
03:13I will save link as, I'm going to just put it in my directory, save it there.
03:23Now I'm going to go back to the command-line and there's the file.
03:30What I'm going to do now is I'm going to open up this file using tar, tar xvfz
03:37and the name of the file.
03:40Basically what it's done is it's created a directory called bw-db and there
03:47it is there.
03:48That's the directory.
03:49So I'm going to change into that directory with cd and here's what we have in here.
03:57So now how you install a module from the command-line without using CPAN is also
04:03very simple and prone to error.
04:06So I'm going to type perl Makefile.pl.
04:10It's a good idea to read the README file and read the INSTALL file.
04:14I'm just going to go through the steps here for you and this actually makes the Make file.
04:20It's called the Make maker and then I'll type make.
04:23Now on a Macintosh before you can install modules using CPAN or the
04:28command line, you need to have Make installed at a very minimum and for some
04:32things you might also need a C compiler.
04:34So it's a good idea to install Xcode, which is on your OS X distribution disk or
04:41you can download it from Apple for free.
04:43So I've done that on this Mac and I have Make installed and so I type make, just
04:50like that and it does that successfully and then I type make test, and it will
04:56run the tests and it says All tests successful and I type sudo make install.
05:03The rest of it, I don't need sudo for, but for the install part I do.
05:07So I type sudo make install.
05:09It may or may not ask for your password.
05:11It didn't ask me because it asked for my password a couple minutes ago.
05:15After a certain timeout, it'll ask me for my password again.
05:19So this has successfully installed.
05:21We can see that it says installing, installing, writing, appending and it
05:25doesn't give me anything that looks like an error message.
05:29That's how we install a module from the command-line by downloading it and
05:33installing it, if the command- line CPAN is giving you trouble.
Collapse this transcript
Installing modules from CPAN on Windows
00:00Now we are going to install CPAN modules on Windows.
00:05Now, because Perl was designed for UNIX- based systems and Windows is very, very
00:11different from a UNIX-based system, the process of installing CPAN modules is
00:16very different than it is on a Mac or on UNIX-based system.
00:20We are using the active state distribution of Perl on this machine, which is
00:25the most common distribution of Perl for a Windows-based machine and it's
00:30probably what you're using.
00:31So, we are going to be installing our CPAN modules using the Perl Package Manager.
00:36I've got it on my menu here, because I have had it opened already.
00:39But we are going to go and find it in the All Programs, because that's
00:42what you'll be doing.
00:43I'll select the ActivePerl Build and whichever one you have, it's okay.
00:48You select the Perl Package Manager.
00:52It needs to synchronize its database.
00:54It will start with that and that takes it a little moment.
00:56Now, you'll notice that there is a number of buttons here on the left hand side,
01:01and this selects what it is that we are looking at.
01:03This view here is all of the packages that are already installed.
01:08This view here is the ones that have upgrades available.
01:11You don't necessarily need to be upgrading them all the time.
01:15If you don't actually need to update a particular module, it might be best
01:18to leave it alone, because that can sometimes cause problems with the existing code.
01:22We are going to look at the View All Packages, because this will include the
01:26ones that are not installed yet.
01:28I am going to select one of my packages.
01:31I am just going to type BW up here, and that will find the ones that have bw in them.
01:36These two here are packages that I've written.
01:39So, first I am going to select this one here, because I know that this has a
01:42prerequisite that we do not have.
01:44bw-db requires another package called DBD:MySQL.
01:49Because it requires the MySQL system and we do not have MySQL installed on this machine.
01:55So, I wanted just to show you what happens when there is a dependency that is not fulfilled.
02:00So, I am going to right click on this.
02:04You'll see we get a little pop-up menu with just one selection for installing.
02:08You'll also notice there is a plus sign there. That means instead of using the popup menu,
02:11I could just press the plus key on my keyboard. So, I'll do that.
02:15You see that it says depends on bw- lib, and it also depends on DBD-MySQL.
02:22So, I know that DBD-MySQL will not install on this machine.
02:25If I go ahead and select it, it won't complain.
02:28But if I try and install it, it will give me trouble because I don't have
02:31MySQL on this machine.
02:33We are not going to go ahead and install this one.
02:36I'll just press the plus key and that will deselect it.
02:40We are going to install this one, because this doesn't have any
02:43dependencies that were missing.
02:44I'll press the plus key on this one here, we see it is a bw-lib is marked for
02:50install, and it doesn't have any messages about that.
02:54If we want to go ahead and install that, we can press Ctrl+Enter or we can press
02:59this right green arrow key up here. I'll press that.
03:02It says are you ready to install 1 package? I'll click Ok.
03:06It's doing its work and then it says Installing package done.
03:10So, that's really all there is to it.
03:13It's installed the package.
03:15Now, if we look in the details over here, we can see those are all the installed files.
03:20You'll notice that there's some HTML files installed.
03:23That's the documentation.
03:25So if we go ahead and look at the Perl documentation, going to All Programs >
03:31ActivePerl, and just click on Documentation, it will bring up your web browser
03:35and it will bring up the Active State Documentation for Perl.
03:38If we scroll down here into the modules that are installed, and then we go to b and we see BW.
03:45Here's all the stuff it installed.
03:47It installed BW Base, BW CGI, BW Common.
03:51So, there is all of the POD documentation that comes with these modules.
03:57That POD documentation has been converted to HTML.
04:00One of the features of POD is that it's easy to convert it to a lot of different
04:05display formats, and HTML is a very common one.
04:08We'll talk more about that in the chapter on POD.
04:12That's it. We have installed a module.
04:14That's how you install CPAN Modules on a Windows machine.
04:18You don't actually use the CPAN program.
04:21You use the Perl Package Manager, which is actually pretty convenient and
04:24pretty easy to do.
Collapse this transcript
15. Documentation with POD
Understanding POD
00:00POD is how you do documentation in Perl.
00:04It stands for Plain Old Documentation.
00:06And it's called that because at the time when Perl was first created and POD
00:12was first created, the standard in computer documentation was UNIX man pages,
00:18and what POD puts out looks very much like UNIX man pages.
00:23The structure of them, the way that the finished product looks and feels, and
00:28the way that it was used that the UNIX command line was very much like the UNIX
00:33man pages, which at that time was an excellent standard of documentation.
00:38Time has marched on and documentation is much fancier now.
00:42POD is still a really good way to do things because it's basically extremely
00:49simple to use POD to create a uniform documentation.
00:55The syntax of it is easy, how it gets applied to the documents is
01:01easy, everything about it is easy to use, and the finished result is
01:06more than serviceable.
01:07With the various POD translators that are available today and even come
01:11standard with Perl, you can create very fancy looking modern documentation in
01:18HTML and PDF, and a lot of different formats.
01:21The source of it is still this incredibly simple to use syntax.
01:25So let's take a look at how you create documentation using POD.
Collapse this transcript
Documenting with POD
00:00POD documentation is mostly used for modules.
00:03It certainly can be used for any Perl code, but it's mostly used for modules.
00:08Let's take a look at how that is typically done.
00:13Make a working copy of this module here, we'll call it Example.pm.
00:17I'll go ahead and open that up and we'll take a look at the POD documentation
00:23down here at the bottom.
00:25You'll notice that at the end of the code, we have this __END__ directive and
00:29then the POD documentation begins from there.
00:34Here we have a POD directive.
00:36It's the equal sign followed by head1.
00:39That makes a level 1 heading.
00:42We have the word NAME for the heading.
00:44After that, we have just a paragraph of text and then another level 1 heading
00:48that says SYNOPSIS, some more text, and another level 1 heading.
00:54We have this over directive and that makes an indent of four characters.
01:00Then we have an item directive and these could be bullet items.
01:04They're not always formatted with bullets.
01:07How it's formatted depends on the POD processor.
01:10The typical POD processor is pretty plain.
01:13Here we have a formatting codes.
01:15This one is B for Bold.
01:17This word will be in bold.
01:19The formatting codes are one-letter and then angle brackets around whatever it
01:24is that they operate on.
01:25Then we have a couple of more paragraphs, another item and then back.
01:29This undoes the indenting of the over.
01:33That's pretty much it.
01:34At the end, there is a cut.
01:36You could actually have more Perl code after that, except that I used this END directive.
01:42That will prevent any other Perl code from coming after this.
01:46But this is typically the way that it's done.
01:48POD documentation can be, and you'll sometimes see it interspersed with the code.
01:52Most people put it all the way at the end, and that's the really convenient way to do it.
01:57So let's take a look at what this looks like in the Perldoc processor and type in Template.
02:04That will go ahead and bring up the documentation for this module.
02:09Maximize that so you can see it.
02:11That's what the documentation looks like.
02:14It's common to use this format. You have NAME and then you give the name and a
02:20single dash and a one-line description.
02:22SYNOPSIS is used for how the code is used and then methods for the different
02:31methods in the module.
02:33Here we have the new method and what it does, the METHODS method, which is just
02:38a placeholder where you can create your own, the AUTHOR and the HISTORY.
02:44This is all created by this POD documentation.
02:50Looking in detail, head1 creates a level 1 head.
02:53There are four possible levels of headings.
02:56So we could have head2, let's call it SOMETHING ELSE, and a head3, and call it
03:03YET ANOTHER.
03:09If we look at that, go ahead and save this and close this and bring that up
03:16and type in Example.
03:19So, you see that SOMETHING ELSE is intended a little bit more, YET ANOTHER is
03:23indented a little bit more.
03:25That's how those work.
03:26You'll also notice that sometimes I have the text all the way over to the left
03:30and sometimes I have it indented.
03:32There is a reason for that.
03:33When text is all the way over to the left, it's formatted like a paragraph.
03:37For example, if I were to take this line here and just duplicate it a few times
03:42and save that and look at it in the POD documentation, then we see that it gets
03:53formatted like a paragraph.
03:55It ignores these new lines and just wraps it around however it wants to.
03:59On the other hand, if the line is indented at all, it will format it literally.
04:05So you see up at the top here where we have that SYNOPSIS.
04:08That is, it's indented, but it's also formatted literally.
04:11I have one line after the other.
04:13So when you have an example of code, you always need to indent it a little bit,
04:17so that it stays formatted the way that you intended in the documentation.
04:27We'll just get rid of those.
04:31That's pretty much how POD documentation works.
04:34Of course, there are a few other commands.
04:36There are a few other formatting codes and some other details.
04:40If you look in the Perl documentation and you search for perlpod, you'll get the
04:48entire documentation on how POD documentation works and all the different
04:53options that are available.
Collapse this transcript
Exploring a POD document
00:00Let's take a look at a typical POD document, so that we can get an idea of the
00:04kinds of things that go in it and how it typically gets formatted.
00:09This is the documentation for one of my modules, BW::Common.
00:12It's just some common utility functions and this is the source code for it.
00:16It's not a very big module, but it has a few different methods in it.
00:21Here's the POD documentation for it starting down here.
00:24You see it has head1 NAME, and then it has the name of the module and a dash and
00:30a short description.
00:32This is actually used by the CPAN importer to automatically generate a one-line
00:38description for when people do searches in CPAN.
00:42So using this exact format here is a good thing to do if you're going to
00:46publish your modules.
00:49Then there is a SYNOPSIS and this is just typically how you use it.
00:53So, if we look in the actual POD documentation how this comes out, you see
00:58those parts look like that.
01:00Then we document the methods.
01:01So, there is a level 1 header that says METHODS, and then these are all done
01:06with the item command.
01:07So we have over 4 and item, new, item B<comma> number.
01:13Some people will use the parentheses. I use the old UNIX style.
01:17You can do this either way.
01:19It's probably more common to use the parentheses.
01:22So <comma> number returns a comma-fied number.
01:25So this just gives a little description of each of these.
01:28You'll notice with this one, you see the way that it's wrapped here, when I
01:32write it, I tend to put my sentences on separate lines.
01:34It makes it easier for me to edit them later.
01:37The Perlpod processor will typically wrap them around and make them look nice.
01:42So, that's the way that those look and all of those are formatted with
01:46these item commands.
01:48Then we have back and a level 1 header for AUTHOR, a level 1 header for the
01:55COPYRIGHT, level 1 header for the HISTORY.
01:58I indent my HISTORY, so that it will not get formatted, so that it will be
02:02literal, just like with the SYNOPSIS.
02:05Then I format them really nice.
02:06I'll align everything up, so that it's easy to look at the HISTORY and to see
02:10whatever version it is you're looking at, one of the changes. That's it.
02:14POD documentation is incredibly easy.
02:17If it weren't, people wouldn't document their code as easily.
02:20Programmers are notorious for not bothering with documentation.
02:25So the easier you can make it, the more likely it is that the programmers will document.
02:30Using POD is so easy it's actually a pleasure to do.
02:34So there is a typical example of how you can create some simple documentation
02:40using POD to document your modules.
Collapse this transcript
16. New Features in Perl 5.10
Using Perl 5.10
00:00As of this recording, Perl 5.10 is just over a year old and it's still not
00:05very widely deployed.
00:07The very latest computers and the very latest distributions are starting to
00:11support 5.10, but most computers that aren't brand-new still have 5.8 or even 5.6 on them.
00:20So, writing new code with the features of Perl 5.10 will limit the audience of the code.
00:27If you're writing code that's just for your own computer, then go ahead and use
00:31the 5.10 features, but if you're expecting to distribute it and expecting it to
00:35run on somebody else's server, on somebody else's machine, then you really need
00:39to still avoid the new features of Perl 5.10.
00:44Perl 5.10 includes new language features, and these new features are
00:49incompatible with previous versions of Perl 5.
00:53So you just need to be careful when you're using these features.
00:57If you want to use the new Perl 5.10 features, you need to include this pragma,
01:02use feature ':5.10';.
01:07There are a couple of other ways that you can do this.
01:10You can individually select which features you want to use using this syntax, or
01:15you can simply require the latest version of Perl using this use 5.010 syntax.
01:24So if you're going to use the latest features, this is where you need to put at
01:28the top of your program, and in the rest of this chapter we'll look at the
01:31details of how you use some of these new features in Perl 5.10.
Collapse this transcript
Displaying text with say
00:00One interesting new feature in 5.10 is the say built-in function, which does
00:06pretty much what our message function was doing.
00:09Let's take a look at that.
00:10We'll make a working copy of this newfeat.pl file and we'll call it say.pl and open that up.
00:17We've got this use feature ":5.10", that allows us to use 5.10 features, and
00:24there is the say and in fact, this is our whole file now, because we don't have
00:29that message function in here anymore.
00:32Go ahead and run this.
00:33You'll see there it is.
00:35And if we were to put another one on the next line,
00:42semicolon, go ahead andsave that and run it.
00:50see we get two separate lines without having to put a new line characters.
00:54That's what say does.
00:56It's very simple and direct.
00:59In order to use it, you have to be using the features of 5.10 and of course,
01:05this will not run in older versions of Perl.
01:08It doesn't save a lot of work, because obviously it wasn't that hard to have a
01:13message function in there.
01:15But it's a useful shortcut and it will certainly, in the long run, it will get
01:19a lot of use when 5.10 gets deployed.
Collapse this transcript
Selecting from multiple choices with given and when
00:00Certainly one of the most widely anticipated features in 5.10 is the switch
00:06statement, which is not called switch, but it's called switch.
00:11Let's take a look at that.
00:13We'll start by making a working copy of this newfeat.pl file and we'll
00:18call this one switch.pl.
00:21And if you're familiar with any other modern programming languages, you'll
00:25know what switch is.
00:27We've have to have Use feature. At least we have to have the switch statement
00:31mentioned in here, but we can just use this construct of use feature :5.10.
00:35In most languages that have a switch feature, the keyword is switch.
00:42And each of these selections is done with a case statement and so it would look
00:48something like this.
00:49You would say switch and you would have a variable name and you would have some
00:54sort of a block and you would have case and a value.
00:59And you would have some other sort of a block, or indentation or something, and
01:04then you would have case and some other value, and it would work like that.
01:08In Perl, however, they went and changed the name of everything.
01:11And so switch is called given, even though the feature is called switch,
01:16called given here, and each of these cases is called when instead of case,
01:23given this when that.
01:25It's a very nice little syntactic thing to say given and when.
01:30It's kind of a little bit more meaningful in English, but they called the
01:34feature the switch feature.
01:36This is all based on the Perl 6 work that's been going on for at least 10 years,
01:42and is still not even very near to being released.
01:46And rather than wait for Perl 6, people got tired up and they when added it to the
01:50Perl 5.10, so just waiting for Perl 5.10 be wide enough deployed.
01:56There are some great features here in the switch given feature and we're going
02:00to take a look at this.
02:01There is something called Smart Matching, which is actually pretty cool.
02:06Let's define a variable here and start looking at this.
02:11Call this one jimi hendrix and go ahead and we'll say given($s).
02:19Delete all of these and let me format this a little bit.
02:24So the $s is the selector. This is the variable that will be tested in each of
02:28these, and we'll say when say undef, and we'll say $s is undefined, and
02:40we will go ahead and make a few copies of this so we can do some different things with it here.
02:44And when it's exactly a jimi like that, then we'll say '$s is a musician.
02:53And when it matches, say, a regular expression that includes /jimi/.
02:59We can say maybe a musician.
03:08Or let's say when it's a number, an odd number, let me say $s is odd number.
03:24The default would be "is something else."
03:30What's cool about this is we can do all of these different kinds of matches with this.
03:36And this is that Smart Matching that I was talking about and this is new to
03:40Perl, and there are not a lot of languages that do this or at least there's not
03:43a lot of languages that do this well.
03:45When we save this and run it, $s may be a musician, which I just spelled terribly.
03:53Fix that and fix that. Okay, save, run.
03:59Oh that's much better.
04:01And we can take out this here.
04:03So we don't need that anymore.
04:05So, you see that it didn't match undef.
04:08It didn't match this exact match to a string, and it found this regular
04:12expression that it matched.
04:14If instead, I were to make this a 7 like that and save and run, we don't get an
04:21error by trying to match it with the string, or trying to match it with the
04:24regular expression, instead it just goes down there and it finds this numerical
04:28test and it says $s is an odd number.
04:31So this is the Smart Matching feature, which is actually pretty cool, and
04:35certainly the most common.
04:38This is how the switch statement is used.
04:41Again it's called the switch statement even though it uses given and when and default.
04:45It uses the Smart Matching feature that allows you to do a lot of
04:49different kinds of matching.
04:50In fact, there is a whole document with dozens and dozens of different ways that
04:54you can do matching, but these are some pretty good examples of how that's done.
04:58So that's how the switch statement works with given and when and default and
05:03that's available in 5.10.
Collapse this transcript
Keeping persistent variables with state
00:00An interesting new feature in 5.10 is the addition of state variables.
00:05State variables are persistent variables that are locally scoped like my
00:09variables except that they don't get reinitialized every time you start a block again.
00:15Let's take a look at how this works.
00:17We'll make a working copy of newfeat.pl.
00:20I will call this state.pl.
00:22We are using the use feature ":5.10" which is required to be able to use state variables.
00:28We'll go ahead and define a little subroutine here. We'll call this increment,
00:37declare a variable and we will do shift.
00:42And we will say ++$n. We'll increment it and then print it.
00:49Up here we will declare a variable, my $i =5, and we will go ahead and
00:56increment, $i, and we will do that say four times.
01:04So when I save this and run it, we'll see we get the number 6 four times, because
01:10each time $i gets passed,
01:13it gets incremented by one and printed.
01:15It's using this local variable here, locally scoped with my and this one here is
01:21locally scoped with my and never the twain shall meet.
01:24So each time $i gets incremented all over again and it starts all over again and
01:29it's a 5 and this would become 6 and it's 5 becomes 6.
01:34Now, here's the interesting thing.
01:36All we do is change this "my" to "state" and the behavior changes entirely.
01:41What happens is the first time it's used it gets initialized, and then from
01:46then on it ignores this and it remembers what it was the last time and it goes
01:52from there. So just by changing "my" here to "state," watch how this changes the behavior.
01:58Go ahead and run that.
01:59And now we have 6, 7, 8, 9, which is really kind of interesting.
02:03Now the only way to have done this before would have required the use of a
02:08globally scoped variable or using a reference to this scalar out here.
02:14Either one of those things has horrible potential for side effects, name space
02:18collisions, and all kinds of possible problems.
02:22Typically in order to do something like that safely you would have had to have
02:26used a module and again you've got to have a globally scoped variable, and it's just a mess.
02:31Now you can do little locally scoped variable and have it behave in this
02:36unique and interesting way that just makes something like this very, very
02:41doable and very, very clean.
02:43So that is how state variables work, and that's what they are good for.
02:48Of course they are good for a lot of interesting things beyond just
02:50incrementing a variable.
02:52You can use them actually for keeping state in a state machine and that will
02:56work very, very well.
02:58So here's something else that we can look forward to as 5.10 gets widely
03:02deployed: state variables in Perl 5.10.
Collapse this transcript
17. Exploring Web Development
Exploring CGI
00:00CGI is the interface between a web server and a web application.
00:07So CGI applications always run on a Web server; they don't run on your desktop.
00:13You can of course install a web server on your desktop for doing development
00:16work and many people do that but CGI requires a web server in order to run.
00:23To learn more about CGI, I suggest you take the CGI Essential Training course on
00:29lynda.com and that will teach you the details of CGI.
00:32CGI is not a large subject.
00:34It's a relatively small subject.
00:36It's really just about a few protocols about how servers interact with web applications.
00:42In this movie, we're going to look at a couple of examples of CGI
00:45scripts written in Perl. Here's one.
00:48It's the Hello, World written in CGI and this is one of the simpler things that
00:54you can do with CGI.
00:56This is a normal looking Perl script and the first thing here is that it prints
01:01this content type text/html with two line feeds at the end.
01:07That is required to be the first output from a CGI script in a CGI environment.
01:14That tells the server, yes this is a valid CGI script and it also tells it
01:18what type of content.
01:19It can be text/html.
01:20It can be text/plain.
01:23It could be image/jpg, any valid content type, then what comes after it is of
01:28course expected to be that.
01:30This syntax is something that we may not have seen before in Perl.
01:34This is called a here document and this little token here with the two left
01:39angle brackets and the token says to print everything between this and the
01:46same token at the end and so inside of that we have this little HTML document,
01:51which you can see there and it basically prints Hello, World, with a little bit of styling to it.
01:55We can look at that in a web browser and here we have it running on my
02:01server, perl.bw.org. This is hello.cgi.
02:05This is exactly the same script and you'll see that when we View Source that
02:10that is the HTML that we just saw there in the Perl script.
02:16That is a very simple example of a CGI script.
02:20For a slightly more functional example, we have this here, which is test.cgi.
02:27This is the first thing that I will always upload to a server because getting
02:32this to work on a server, it teaches me what I need to know about that server in
02:37order to get other CGI scripts, other more complicated CGI scripts, to run.
02:42So I'd like to start with something simple just to focus on the mechanics.
02:46You know, what does the server require in order to run CGI. All servers have
02:51different requirements.
02:52It may require that the file be named a certain way.
02:55It may need to say .CGI at the end of the file name.
02:58It may need to say .PL for Perl at the end of the file name.
03:01If it's a UNIX server, it's going to need certain executable permissions and it
03:06may need to be in a special directory.
03:08It may need some configuration set.
03:10So whatever those requirements are, the process of installing this one simple,
03:15one file small script is going to teach me what that is and what it is that I
03:20need to know about that particular server in order to run CGI and once I have
03:25the script running then the output of the script will tell me even more about the server.
03:31Here I can see all of the server's environment variables, all kinds of
03:34things about the server.
03:35What server software is running on it. It's got PHP installed, what is the
03:40absolute path to my scripts, things like that that I might need to know in order
03:44to configure my scripts and in order to get them working well.
03:48In my usage of it, this is a vital step in installing any CGI on a web server.
03:55Finally, once we have done that then we can look at installing an application.
04:00For example, this is the bw-contact application that's developed in the CGI
04:06Essential Training course and this is a bit more complicated script.
04:10This is about 250 lines of code and it involves a directory of HTML files that
04:16are used as templates in order to format things on the screen and this is what
04:22it looks like when it's running on the server.
04:25It presents a contact form and you can tie things into it and it'll interact
04:30with you and it'll send a piece of email.
04:33That example is here in the directory and you can look through it.
04:38Some interesting things that you'll notice about it and we'll talk about this a
04:41little bit more later on in this chapter, you'll notice that it uses a number of libraries.
04:46I find it very valuable to take the parts of those applications that I seem to
04:53be using over and over again and to put them into libraries.
04:57You can find a lot of libraries on CPAN and a lot of libraries are fairly
05:01complete and have a lot of these functions already in them. I've tended to
05:04collect my own and you know for some of that time there might not have been a
05:08lot of other choices.
05:10But today there are and you can certainly look at all of those and these are
05:13also available in the CPAN repository.
05:17So this is an example of a CGI application that interacts with the user and
05:23sends email and in the rest of this chapter we'll be looking at a couple of
05:26other examples as well.
Collapse this transcript
Using a database
00:00As you're building a web applications, one of the things you're going to want to
00:04do often is to use a database.
00:06So, we are going to take a look at an example of how that's done in Perl.
00:11We'll take a tour through a database application and see the various different
00:15functions and how they are implemented in Perl.
00:19First, I want to direct your attention to the RandomQuote application that we've
00:23been dealing with throughout this course, and you'll notice that it has this
00:27quotes.txt file and this is a flat-file database.
00:32It's a very simple form of a database, but as fields and it has records and it
00:37has data and that makes it a database.
00:41The problem with the flat-file database, it can be very useful for small amounts of data.
00:45But once you get to have any more data than say what we've got here it starts
00:49to become unmanageable.
00:51So, that's why there are more powerful databases available.
00:56Here, we have an example of a database management application that does the four
01:01functions of a database:
01:02create, retrieve, update and delete.
01:05This is a testimonials database for this web application here.
01:10You'll see this little box there.
01:11They are testimonials.
01:12Well, it's loaded with just the little silly quotes from my quotes database.
01:16But this is where testimonials would be where you can say oh, your website is wonderful.
01:20I love your products, and it's by S. Dali and M. Twain.
01:26This is the application for managing that database.
01:29So you could have hundreds or some greater number of different quotes in that
01:34database and it would be relatively manageable.
01:37Here we are just showing five per page, because we have limited screen real estate.
01:41But normally there will be 10 or 20 or 50 per page.
01:44You can look at page 2 and you can look at page 3.
01:48You can look at them. Add one.
01:51This is a new quote by B. Weinman, and you can add that to the database. You can edit it.
01:58You can say this is a very new quote and you can update that.
02:02Then delete it if you decide you don't want it in there any more.
02:05This is what it makes it easy to manage a sizable amount of data.
02:10So, let's take a look at how this is done in Perl.
02:15Here in Eclipse in the Chapter 17 Web Development folder in your Exercise
02:20Files, you'll see a folder called twotrees and that is that a twotrees web site.
02:27Under twotrees, you'll notice a folder called testimonials.
02:32In that folder, you'll see this db.cgi.
02:36Here, in this file up at the top you'll notice that it imports a lot of modules.
02:41These are modules that I have written.
02:42I have built over the years from all of the codes that I wanted to reuse.
02:47This is what you'll do as well.
02:48We'll talk about that process in another movie in this chapter.
02:52But for now I want to direct your attention to this one here that says BW::DB.
02:56We are going to go ahead and open that. That is this DB.pm.
03:02So this is the module that's being imported here.
03:06Use BW::DB and DB.pm.
03:09So in the db.cgi file let's take a look at some of the database operations and
03:14see how they're done.
03:16If you look at addrec, this is where record is added to the database.
03:20Records in this application are all kept in a common format.
03:25They are all kept in a simple hashref.
03:27I pass records around in a hashref that I typically name rec.
03:32So, record is passed into this function, rec=shift, and that's how we pass
03:37things into a function in Perl.
03:41So, it's in this hashref, which is easy to pass around.
03:45So, testimonial is filled in from the cgi and byline is filled in from the cgi.
03:54Then we have these two fields in our hash, and that is passed in this hashref to
04:00a function in the database module called Insert.
04:05It gets the name of the table, the hashref with the record.
04:09Then over here in the DB module we'll look for the function that says insert,
04:16and there it is and this is what happens.
04:20Now insert get three arguments, and they are self, because all modules get that
04:27as the first argument, even though it's not explicitly passed.
04:30Because DB here is an object, when that method gets called, the first argument
04:36is going to be the reference to the object itself, which is usually called self.
04:42Then the table name, and then the hashref with the name/value pairs.
04:46So, I call it here nvpairs.
04:49Those nvpairs are then are read in this foreach loop.
04:53So, we get an array of columns and we get an array of values from the keys and
04:58the values in the nvpairs.
04:59Then that is taken and an SQL query is built out of that.
05:06That SQL query is then passed on to the database interface, which is something
05:11called DBI, which is used for virtually all database work or most database
05:16work in Perl anyway.
05:18You rarely see anything that's not DBI.
05:20So, here at the top we have this use DBI and that is what this $self->{dbh}
05:28here is, actually a reference to that object.
05:31Then it uses this do method and there we see all of the description of that do method.
05:37The $query is passed which is this SQL that we have just built and we insert the
05:42data into the database.
05:44You can see the power of using an interface like this.
05:49We can do things very simply by just passing around these hashrefs for all of
05:54the database operations.
05:56So, that's the most complex of them.
05:58the rest of them are actually pretty simple.
06:00getrec actually does its work with a simple database query, because it doesn't
06:07need to do in a complicated building of the query.
06:10It does this and sql_ select inside the DB module.
06:15It will go ahead and create a hashref, which will have the data in the
06:18right format already.
06:21Likewise with updaterec, I tend to name them so that it's really obvious what they do.
06:29It uses a simple SQL query to update the database.
06:34It uses a method called sql_do in DB.pm.
06:39Likewise, deleterec, which deletes a record from the database using a
06:44very simple SQL query.
06:48Finally, we have listRecs.
06:51This one is a lot of fun, because this is what does that paging.
06:57Here's the paging logic here.
06:59We look at this on the paging function here.
07:02We have the ability to go to the next page and the next page.
07:06So, these are previous and next buttons, where we can jump directly to
07:10an individual page.
07:12All of that logic is right in here.
07:14Because so much of the work is passed off to these modules and to even other
07:19functions within this application, it really just comes down to this simple if
07:25else for handling the next page, previous page, and the page jump buttons.
07:30We simply update a page number with each of these, we increment it for next page,
07:33we decrement it for previous page, or we update it with a particular page
07:38number with the page Jump.
07:40Then we do a small amount of math here to figure out the offset from that.
07:45Then we put that into the SQL using this LIMIT structure now.
07:49Every SQL engine has a slightly different syntax for this.
07:54If you are interested, take a look at the SQL course here on lynda.com,
07:58SQL Essential Training.
08:02So, this is basically the meat of the database management application.
08:06You've got all the code here, you can look through it with your knowledge of
08:10Perl from this course, and you can probably understand most if not all of it
08:14from that, and get an idea of how you build a database application using Perl.
Collapse this transcript
Developing a module library
00:00As you work with Perl, over time you're going to come up with a number of
00:05functions and a number of routines and number of pieces of code that you like to use,
00:09 that work the way that you like them to work and that you will reuse over
00:13and over again and you should put those pieces of code in modules because that's
00:18the unit of reuseability that Perl uses.
00:21Here is a list of modules.
00:23These are some of the modules that I built over time and you have in your
00:28exercise files here all of these modules.
00:31These are most of the modules that are used in my everyday work in the Perl language.
00:37So here we've included a few of them in this file.
00:40This is the db.cgi.
00:42This is the database management application for the twotrees web site and in
00:47building this application I reused a lot of code that I've developed over the
00:53last 15 years or so.
00:55And so what I'd like to do is I'd like to show you some of these modules, not so
00:59that you'll use these modules but rather you'll get the idea that as you learn
01:05to work the way that you like to work and as you come up with code that works
01:09the way that you like it to work, that you will build your own module library.
01:13And your module library will look entirely different than my module library.
01:17And it will work the way that you work, while mine works the way that I work.
01:21Now CPAN, the Comprehensive Perl Archive Network, has a number of modules
01:27available to do a lot of these same things.
01:31You're certainly welcome to use those modules.
01:34As you do, you'll find that they all have their own way of doing things.
01:38For example, the error reporting, as you use those modules, you'll find that they
01:43all have their own way of doing error reporting.
01:45So you'll have to find the errors and check the return codes of all of these
01:49different functions in umpteen different ways and you may find that
01:53frustrating as I have.
01:55And so a lot of times like in the case of this DB module, I've simply taken a
02:00library of modules from CPAN. In this case that would be the DBI library.
02:07And I've just wrapped my own code around it, so that it works the way that I like it to work.
02:11Their functionality is great. It's reliable. It's bug free.
02:14It's pretty much the standard way of interfacing with databases in Perl and yet
02:19I would like the error reporting to be the way that I do error reporting.
02:23I would like the way that it passes data to be the way that I like to pass data.
02:27So that all of my code, when I'm building an application like this, I can do in
02:31500 lines when it might otherwise take me a thousand or several thousand lines
02:36of code to do, if I have to use all of these disparate modules that do things in
02:40all of these different ways.
02:42And so as you build your portfolio of code in the Perl language, Perl has this
02:48great module system and so I encourage you to use it to build a library of
02:53modules that work the way that you work, so that your code can be more
02:57efficient and effective.
02:58So let's take a look at what some of these things do.
03:01Now know all of these modules if we take a look here DB.pm, they all start with
03:06a use base BW Base.
03:09And so what that does is it takes this base module and it inherits from this
03:15base module the common things, for instance the constructor.
03:19I don't need to write this over and over again for each one of my modules.
03:23I can write it once and inherit it. This init, which is fairly complex and what
03:29this does is it allows me to pass all kinds of values into my constructor and
03:34to build a set of properties for the object, and it use this generalized setter getter.
03:43There's a common debug method that gets imported by all of my modules.
03:47Probably the most powerful thing in this entire library is this simple error
03:52reporting, which is these three functions. error,
03:55underscore error, which is only used internally, the error without the
04:00underscore, which is used for getting the error message and the checkerror,
04:05which is used from all of my different modules for checking errors as they call each other.
04:11It just looks very simple here but the fact that I have this makes my coding so
04:16much easier because the weakest part of Perl is in its error reporting.
04:22Even this is a little bit kludgey but it works and it's consistent and I use it
04:27across all of my modules and they all end up working the same way.
04:32So let's take a look at the CGI module.
04:36This is one of the most common ones that I use.
04:38Now there's a very popular CGI.pm that comes with your Perl distribution
04:43that most people use.
04:44It's very big, it's very complicated, and it does a million different things
04:49that in my opinion are mostly tangential to CGI.
04:53CGI is a small subject. CGI is just a few things.
04:57It's about setting a query string.
05:00It's about using cookies, setting headers, and it's about displaying the text
05:08on the web browser.
05:10My CGI module is relatively short.
05:13It's about 400-500 lines including the documentation.
05:17It just does these few things that your average program needs to do with CGI
05:23and the other things that you might find in the larger CGI libraries, I will
05:28have those in other places. Like I have a separate HTML module for like building
05:34a select box, for forms, and a separate address code module which simply has
05:42data of two-letter address codes for states and for countries for building the
05:48little select boxes.
05:50These are the kinds of things that some people tend to pile all into one big module.
05:54I like to separate them out so that I only need to include them when I need them.
05:59But the point is not for you to do things the way that I like to do them,
06:03but for you to find the ways that work for you. As you do that, to build your own
06:09module library that works the way that you work.
06:12That will result in you're being able to build your applications with less code,
06:19spending more of your time looking at the logic of the application that you're
06:23building, and not having to worry about all of these different ways of doing
06:29things, to just be doing things the way that works for you, and then you'll be
06:34able to focus your effort more on building reliable and powerful applications
06:39using your own library of Perl code that you've collected and reused over the
06:45course of your work.
Collapse this transcript
Conclusion
Goodbye
00:00In this course, my goal was to give you a good foundation in Perl with all its
00:05major features and properties so you can use it to build powerful and
00:08compelling applications for yourself and for your clients.
00:12I've covered the basic syntax of Perl, its use of lists and hashes for data
00:16structures, its unique features like postfix conditionals and loop controls,
00:21its modules and its object model and I have walked you through some real
00:25applications so you can see how to apply your programming knowledge to building
00:29your own Perl modules and applications.
00:32I've really enjoyed creating this course for you and I sincerely hope that it's
00:36as useful for you as it has been fun for me.
Collapse this transcript


Suggested courses to watch next:

CGI Essential Training (1h 33m)
Bill Weinman

Python 3 Essential Training (6h 36m)
Bill Weinman


Are you sure you want to delete this bookmark?

cancel

Bookmark this Tutorial

Name

Description

{0} characters left

Tags

Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading
cancel

bookmark this course

{0} characters left Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading

Error:

go to playlists »

Create new playlist

name:
description:
save cancel

You must be a lynda.com member to watch this video.

Every course in the lynda.com library contains free videos that let you assess the quality of our tutorials before you subscribe—just click on the blue links to watch them. Become a member to access all 98,755 instructional videos.

start free trial learn more

If you are already an active lynda.com member, please log in to access the lynda.com library.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Access to lynda.com videos

Your organization has a limited access membership to the lynda.com library that allows access to only a specific, limited selection of courses.

You don't have access to this video.

You're logged in as an account administrator, but your membership is not active.

Contact a Training Solutions Advisor at 1 (888) 335-9632.

How to access this video.

If this course is one of your five classes, then your class currently isn't in session.

If you want to watch this video and it is not part of your class, upgrade your membership for unlimited access to the full library of 1,899 courses anytime, anywhere.

learn more upgrade

You can always watch the free content included in every course.

Questions? Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com.

You don't have access to this video.

You're logged in as an account administrator, but your membership is no longer active. You can still access reports and account information.

To reactivate your account, contact a Training Solutions Advisor at 1 1 (888) 335-9632.

Need help accessing this video?

You can't access this video from your master administrator account.

Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com for help accessing this video.


site feedback

Thanks for signing up.

We’ll send you a confirmation email shortly.


By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked