Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Perl Babysteps 1: Your First Simple Script

by webfiend (Vicar)
on Dec 30, 2004 at 00:10 UTC ( [id://418141] : perltutorial . print w/replies, xml ) Need Help??

Note: This copy of the tutorial has been going stale as Perl moves on. There is another descended from the same material on my own site. I haven't decided yet whether to update this page and add the material that has been added to Perl Babysteps tutorial since then.


This page is intended to provide the non-programmer with a gentle introduction to the Perl programming language. When you are done with it, you should feel ready to learn more. You will not be an expert, but you will be able to find the information you need to go farther. Beginners and experts alike should feel free to send suggestions about how to improve this tutorial.

Installing Perl

It is very easy to find and install a copy of Perl for your operating system. How easy? Well, it's a single simple download, and you may already have it on your machine!


Well, okay. If you are using a Windows machine, you probably don't already have Perl on your machine. But it's easy to get. You even have a couple different versions to choose from.


This is the officially blessed version of Perl for Windows. It is released by ActiveState. ActivePerl can be downloaded for free, or you can order the ActiveCD from them. It comes with a wealth of widely used third-party libraries such as Tk, LWP, and the XML bundle. Whether you choose to download or purchase, here is your best starting point:

Perl on Cygwin

On the other hand, maybe you prefer to have Windows with a touch of UNIX on top. First, I want to let you know that Perl is perfectly happy under Windows these days. But if you insist, or just happen to be curious, Perl is also available for Cygwin. Just rerun Cygwin's setup.exe program, and make sure that "Perl" is checked. Oh, and add an editor while you're at it, too. Maybe Vim or Emacs.

Everybody Else

You probably already have it, especially if you happen to be on a UNIX-based operating system such as Linux, FreeBSD, or Mac OS X. Seriously. Try the which command if you don't believe me.

$ which perl /usr/bin/perl

That'll teach you to doubt me. Just kidding. If you don't have it installed, you'll get a message along the lines of perl not found in .... Double-check to see if it's on your installation media. For OS X folks, you just need to install the Developer Disk.

The Macho Geek Option: Compile From Source

Whatever operating system you are on, this is a valid choice. Still, there are a lot of options when building. It can be more than a little overwhelming. I would suggest you go with one of the available binary downloads while you're just starting out.

Creating Perl Programs

The tradition in programming literature is to start by creating a program that prints a simple phrase, such as "Hello, World!" The idea is to give you some clue how much work is involved in creating a minimal program. I, for one, am not going to argue with tradition. Not this one, at least. Type the following into your text editor:

# # - Displays a warm greeting print "Hello, World!\n";

Save the file as We will run it in a few moments, but first, let's take a quick look at what we've got so far.


On each line, everything from # to the end of the line is a comment. Perl ignores comments, so they allow you to communicate with other people who read your code. Comments are very very good. When you come back to look at a complex script after a few months, you might forget what some block of code does, or why you chose one solution over another. Having the comments there help to remind you what you were intending, and generally serve to make it much easier sorting everything out.

I like to start all of my scripts off with a quick header to describe the purpose of the program. Here is a rough template:

# # Displays a warm greeting.

All we have is the name of the file and a brief description of what the program does. That is often all that you need, especially for simple scripts like this one.

NOTE: The official documentation system for Perl is POD, or "Plain Old Documentation". It is powerful and widely used, but it is also beyond our scope for this stage of the tutorial. However, to give you a little taste of how much easier POD makes life, here is the first sentence displayed after you type the command perldoc -f print at the command line:

Prints a string or a list of strings.

You should read POD in 5 Minutes if you are curious to learn about how to format POD documentation for reading with the perldoc command.

Now you would probably like to know how to actually run your program. Save the file you have been editing and switch to a command line. Make sure you are in the same directory as your script - this should be as simple as cd project_directory. Once you are in the right place, type the following into the command line:

$ perl Hello, World! $

Oh, what was the "\n" at the end of the string for? That is a fair question. It's a special code for the newline character. What's the newline character do? It's easier to show you what happens when you don't have it:

 print "Hello, World!";

Save it and run it.

$ perl Hello, World!$

Adding a newline character in the string tells Perl that you want to print a new line. Now do you see?

All this is kind of cool, but it would be nice to customize it a little bit. Maybe we could change the program so that it says "Hello" to us personally.

# # Displays a warm greeting. my $name = "Brian"; print "Hello, $name!\n";

Now you might notice the semicolon at the end of each line. What? You noticed them before? Well, you're quicker than me. Perl recognizes the semicolon as the marker which ends one statement. So each statement must be terminated by a semicolon. Putting them on separate lines like that is something that Perl doesn't care about, but you might lose friends if you tried to put everything on one line.

Now -- what? Another question? Okay, go ahead. What's that my doing? We use the word my to declare variables. Declaration is when we tell Perl that we have a variable we plan on using. The language doesn't require declaration, but it is good form, and you will find your code easier to debug later on as you learn more about clean programming.

What's a variable? We'll get to that in a second. I'm impatient to see a running program! Save the file, and run it again.

$ perl Hello, Brian! $

There, I feel better. Let's move on to talking about variables.


We stored the string "Brian" in the variable name. A variable is basically just something you want the computer to remember so that you can get to it when you want it later. You can get a lot more complicated than that if you want, and a lot of programmers do. However, this definition should hold us over for a long time.

The "$" symbol at the beginning tells Perl what kind of information this variable holds. Perl basically has two kinds of variables:

  1. Individual things like strings and numbers
  2. Collections of things like lists and dictionaries

When you start digging in, you will see how broad of a generalization I've just made. Still, I think that this will last us until the end of this article, and the basic idea holds true for a lot of Perl programming.

Anyways. Individual things are also called scalars by people who think that you don't have enough things to remember. Ah well, we'll get used to it. To their credit, "scalar" is a shorter term than "individual thing". Perl makes it easy to recognize a scalar, by making you prefix all scalar variables with a dollar sign. So $name is "the scalar variable name", or even "the individual thing called name". Eventually many Perl hackers end up calling it "dollar name".

 my $name = "Brian"; # My scalar variable called 'name' has the value "Brian"

Having a program that displays the exact same message every time you run is nice when it comes to being consistent, but not so entertaining as a program. "What does it do?" "It prints out my name." "Oh." See? Boring. Let's make things a little more interesting. We could change the value of name in the code, but it might be a little tiresome to do this before showing it to each new person. How about making the program ask for a name? User interaction - a neat idea.

print "What is your name? "; my $name = <STDIN>; print "Hello, $name!\n";

We only made one small change, but I'll admit that there's a lot going on with that one change. Here's the short version:

<STDIN> gets input from the user that you can save in a variable.

There's a long version. Feel free to skip it if you just want to get on with it. The long version works out like this:

The scalar $name is assigned the value of <STDIN> . <...> tells Perl that we want it to read a filehandle and hand the results back to us. A filehandle is a source of information. It could be an open file, but in this case it is STDIN. STDIN is the standard input stream - geek talk for "wherever we expect user input to be coming from". Most of the time, STDIN just means "keys the user enters from the keyboard". The result of reading from the filehandle (in this case, STDIN, which is in this case the text you entered from the keyboard) is stored in $name.

There's a really long version, but I'm getting bored so we'll skip it for now.

$ perl What is your name? Brian Hello, Brian ! $

Hey, what happened? The exclamation is all the way on the next line!

Calm down. Everything is going to be okay. Perl just counts the ENTER key at the end as a part of the input, and ENTER prints out as a newline ('\n' if you've been paying attention). Counting the newline is fine for reading text from a file, but it's a little inconvenient when you are handling input from the keyboard. Fortunately, there's the chomp function. What's it do? Let's ask perldoc -f chomp. On second thought, let's not. You can go right ahead, but I just did, and discovered that the docs for chomp are a little dense for today. Let's try mine:

chomp removes the last character from a string, but only if that character is whitespace or a newline.

Let's give it a try.

print "What is your name? "; my $name = <STDIN>; chomp($name); print "Hello, $name!\n";

You already know what chomp does, so running this script shouldn't provide any surprises:

$ perl What is your name? Brian Hello, Brian! $

... and we're done!


Nice work! You have begun to learn Perl by writing a complete program which gets input from a user and prints output including a modified version of their input. Stop for a minute and think about it. Yes, there is much more to learn, but you have dipped your toes into the pool. Now you can go out there and start learning about the huge and wild world of Perl programming.

Additional Resources

Here are a few links to resources that you can use while learning about Perl and how to use it for your own nefarious purposes.

There are a lot more, but I can't recall many of the links right now. I may put them up as time goes on.

Update:(30 Dec 2004)
Removed an aside about complicated script headers, since Juerd pointed out that Perldoc is a better choice for such information, and Anonymous Monk helped me realize that it may be a bit much to expect a total newbie to know when the extended information becomes necessary. If you want to know what that extended header looked like, check the first reply from Juerd. He was gracious enough to reproduce it in its entirety while making a much better suggestion. I also went ahead and did some formatting adjustments (replacing PRE blocks with CODE blocks).

Threw in some suggested links from kutsu, too.

Update:(26 Jan 2005)
Fixed several typographical errors pointed out by erix

Update:(9 May 2006)
Fixed a few markup issues and added link to -- thanks jdporter

Replies are listed 'Best First'.
Re: Perl Babysteps 1: Your First Simple Script
by Juerd (Abbot) on Dec 30, 2004 at 09:04 UTC

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Displays a warm greeting. # # AUTHOR # Brian Wisti (or webfiend on perlmonks) # DATE # 28 December 2004 # VERSION # 1.0 # PURPOSE # Demonstration script for my Perl tutorial # USAGE # perl # LICENSE # You may copy and redistribute this program as you see fit, with n +o # restrictions. # WARRANTY # This program comes with NO warranty, real or implied. # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    You meant

    =head1 NAME - Displays a warm greeting. =head1 USAGE perl =head1 DESCRIPTION Demonstration script for my Perl tutorial =head1 LICENSE You may copy and redistribute this program as you see fit, with no res +trictions. =head1 WARRANTY This program comes with NO warranty, real or implied. =head1 AUTHOR Brian Wisti (or webfiend on perlmonks)
    and the version in the package global $VERSION, I hope.

    Don't document in comments. See also POD in 5 minutes. It's not scary.

    Juerd # { site => '', plp_site => '', do_not_use => 'spamtrap' }

      And it's easier to teach one thing early on and expand that knowledge later. If you teach to much, they will not retain the information.

      For example, on day one you show them comments.

      "Comments begin with the hash (or octothorpe) character."

      # I am a comment!

      And leave the POD for a later day...

      "Today we will learn about POD. POD is short for Plain Old Documentation and it is a fairly simple way of documenting your code. We'll begin by adding a heading to your existing project and then cut back to the code."

      package Beginner::Project; use strict; use warnings; # may or may not be lots of code here =head1 NAME Beginner::Project - a project worthy of a beginner Perl programmer =cut # your code continues here... 1;

      It's scary for the people I'm writing to :-) Tutorials like these are for my dad or brother, who have never fiddled with another programming language for more than a few minutes. The script header bit is just getting them into the habit of documenting in the first place. I agree that once they're ready for POD, they should switch over. But as it is, I'd have to explain POD, formatting, perldoc, and package global variables (which means I'd have to at least glance at packages and scoping).

      A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Perl Babysteps 1: Your First Simple Script
by kutsu (Priest) on Dec 30, 2004 at 20:42 UTC

    Having learned C/C++ in a highschool class and Java/perl through a college class, with much self-teaching on all accounts, I like tutorials like this; that give a very basic idea of a perl script that one can build on. These types of tutorials are very helpful for those who are not programmers by nature or trade, and merely wish, or are forced, to learn a new skill.

    I would like to point out two things: a direct link to the llama book would be nice and a link to woolfy's Where and how to start learning Perl (which is basically a thread of Additional Resources)

    "Cogito cogito ergo cogito sum - I think that I think, therefore I think that I am." Ambrose Bierce

      I think this is an excellent tutorial. I have also had a few programming languages, C+/Java/Pl/sql and I think for the noob thats just getting started, this is a good, very light, non-intimidating overview. Kudos.
Re: Perl Babysteps 1: Your First Simple Script
by Anonymous Monk on Dec 30, 2004 at 09:57 UTC

    Try to match the header complexity to the program, though. Using this header for a program that consists of one line of code might be a little bit of overkill. I usually start with the two-line header and expand it as I see fit.

    Oh, I got to ask this. What will be the two lines you start with, and how large does your program need to grow before you add, say, the name of the author, a paragraph about usage, or a version on it? If you expand it, in which order do you add the things your example has?

    Whether I slab on comments like author, version, date, usage, etc, on a program has all to do with the purpose and intended usage of the program. And nothing at all to do with its length.

      Thank you for the comment, that's a good point. I think my original intention was that the author should add the extra information when he expects other folks to take advantage of his script.

      Hmm ....

      But by that point juerd's suggestion about using POD becomes even more relevant. The long script header thing is really a digression from the main point, and has caused a little bit of bad blood in the threads already, so I think I will take that out completely.

Re: Perl Babysteps 1: Your First Simple Script
by sinfulhealer (Initiate) on Oct 04, 2017 at 12:13 UTC

    Thanks for this, webfiend.

    I was pleased with the tutorial - neither just kick around the bucket nor loads of stuff to take in. Also: you explain in a "conversational manner" (if I may call it that :3), I appreciate that in an introduction! Makes it less heavy to take in. I as a neophyte appreciated this.

    As for me: now I'm moving on to make some text-based adventures! woopwoop :D Feels like a nice way into Perl for me, oh and linked here's what my first ever Perl document looks like!


Re: Perl Babysteps 1: Your First Simple Script
by DaWolf (Curate) on Dec 30, 2004 at 15:10 UTC
    ++ webfiend!

    Well written, easy to follow and clear.

    I've found the statement on your site ("Perl: easy to learn, but hard to teach.") kinda funny and kinda true. You certainly made this easier with this tutorial.

Re: Perl Babysteps 1: Your First Simple Script
by jfnutcase (Initiate) on Aug 05, 2005 at 18:34 UTC
    kudos! Yes, it is a very basic program Hello world! but oldies are goodies. I wanted to compliment or your format. and your comments let me know that at least im not the only one that talks to themselves. ## yes you are. keep up the good work and may the force be with you. ~jfnutcase
      I would like to just say that the flames were obviously from people who KNOW perl and therefore think that this is a low level tutorial... you already KNOW this stuff so shuttup. Conversely, the kudos were from the people who benefited namely people who have taught themselves or people who needed this tutorial. The flames were ridiculous and nonsensical. I appreciated this look on the language. People need to start somewhere and this was very helpful. A starter tutorial has nothing to do with stupid people nor teletubbies. This tutorial helps people just getting started with perl and is (i assume) not intended for experienced people, therefore it helps alot. Hello World is a start almost every beginners book looks at. You did very well and I'd like to say you were more clear than "Perl for Dummies" which I started with because I needed the clarity that came with basic tutorials. all in all, good job, old fellow. carry on. -Stephanie
        First - Thank you for writing this document. Taking the time to enlighten others is highly commendable.

        For those who flamed - It's obvious that you're passionate about perl, otherwise you wouldn't bother answering questions here. This person put forth something to help others perform and understand. You have the brainpower, be a productive source of information for this writer.

        Was there anything technically wrong or misleading in the document? What could be done to improve the clarity? Is it focused and phrased for the intended audience? As a skilled resource, these are the sort of things you should be considering and commenting on.

        Few people realize how many non-technical people are forced into technical roles at their work. I've met more admins who've had root access to production servers than I'd care to admit. They don't get any technical training, don't have any previous background, yet their jobs require them to do "administrative functions" like create accounts, schedule batch runs, you name it.

        If people don't learn perl here, they will learn it elsewhere, and then generate more useless, convoluted scripts all over the place for the next engineer to forklift rewrite.

Re: Perl Babysteps 1: Your First Simple Script
by brusimm (Pilgrim) on Dec 28, 2006 at 05:45 UTC
    Thank you webfiend

    The need for a basic outline to things known by experienced writers is soooo appreciated.

    Whenever I have an inquiry, I search through the SuperSearch, the regular search and the tutorials. If I can't find it, I post an inquiry for Seekers of Perl of Wisdom, with as much detail or clarity as I can, & I annotate my inquiry title at the end with for BEGINNERS so that others in my shoes can see this may help them more than other nodes as it comes from their perspective.

    Face it, at certain levels of experience, you just don't realize what you do know and who doesn't exactly know how to connect the dots. The basics are appreciated..

Re: Perl Babysteps 1: Your First Simple Script
by ruzam (Curate) on Mar 31, 2008 at 19:02 UTC
    My only comment is that you please add the 'use strict;' and 'use warnings;' lines to your hello world script. Even if you gloss over them with a "well talk about those more later" comment.

    I started down my Perl path without strict or warnings. When I started to see them in use (and use them myself) it was awkward annoying (all those new warning messages to wade through). It wasn't until later that I finally came to realize those warnings were for my own good and learned to embrace strict/warnings. It would have been easier and more productive to learn that lesson from day one.

      I think it's about time for a significant rewrite of this tutorial. I agree that strict and warnings are important practices, and I am working through how to introduce them without scaring away the people I am writing for. I wrote an updated version on my own site, but it ended up being so long that I needed to split it into multiple pages (Part 1, Part 2). Part of that is because I am incredibly long-winded, but it's also related to the fact that we are describing ways to change the fundamental behavior of Perl to somebody who does not yet understand what that basic behavior is - or why he would want to change it.

      So, yeah. I need to improve this tutorial, but I need to figure out the best way to do that while still being helpful for my original target audience.

Re: Perl Babysteps 1: Your First Simple Script
by Obi-John (Initiate) on Feb 14, 2005 at 09:10 UTC
    Please fix the script - the last couple of examples are missing a semicolon which causes perl to throw an error and quit. Which line? this line: print "What is your name? ";
Re: Perl Babysteps 1: Your First Simple Script
by Anonymous Monk on Nov 27, 2014 at 12:25 UTC
    Thanks for the great intro to some basic Perl. I've been studying Perl intermittently, but haven't got around to actually writing and running a script yet. Seeing how basic I/O and text handling commands are actually used in a script is giving me more clarity and confidence to start.
Re: Perl Babysteps 1: Your First Simple Script
by mortalhero (Novice) on Sep 10, 2009 at 20:09 UTC

    This was a great start for me. Thank you. I'd like to make a suggestion. It should be emphasized that Perl must be installed first or nothing will happen when you run I tried to jump the gun and found out the hard way. Baby steps for a baby's mind. Thanks again!

      It should be emphasized that Perl must be installed first or nothing will happen when you run
      Exactly how should it be emphasized more than it already is? The second section is titled in big, bold letters: Installing Perl

      This section provides 4 different pointers on installing Perl.

      The install section is followed by the section which tells you to run The author reasonably assumes that the sections are read in order.

        I think this is a great tuturial. Thanks for sacrificing your time for others
Re: Perl Babysteps 1: Your First Simple Script
by Anonymous Monk on Jul 11, 2012 at 00:12 UTC
    best intro tutorial ever! Thanks a lot for putting it together.
      Thanks a lot for the great tutorial, it really helped. Thanks, R. Singh
Re: Perl Babysteps 1: Your First Simple Script
by imusimu (Initiate) on May 10, 2015 at 05:21 UTC
    my $name = <STDIN>; what is my written for before $hame?

      See my in perlfunc.


      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
Re: Perl Babysteps 1: Your First Simple Script
by Anonymous Monk on Oct 21, 2008 at 21:17 UTC
    I LOVE this tutorial! Yes, I know I have a LOT to learn, but being able to understand and actually write the program makes me feel good about myself and encourage continuing learning! I wish you had more stuff in this tutorial! Thanks! Lena
      Bah, when I was first learning HTML, the book I started with just gave us the doctype, went on from there, and later got back to it with a better explanation-- that's what I'd do with the use strict, use warnings-- just tell people to stick them in there, add a sentence stating what they do and that they'll get more explained later, and you're good. No need to discuss it for two pages on a new tut.
      Someone wrote:
      "But that doesn't mean I think we should encourage non-programmers to become programmers. I'm convinced good programmers are more or less born like that, and that they only need to learn to use the appropriate tools."
      I'm a eugenicist myself, but even I wouldn't go that far. Watch out! I'm an idiot non-programmer who can add 2 and 2 and get 4, 5 or 6, and I'm going to use these plain-English tutorials to start desecrating the Perl language like you wouldn't believe! I will fill the nodes and cb with n00b questions and I will start out writing stupid teletubbie programs while I still don't know what I'm doing, and then some, and you won't stop me! I will learn a programming language, learn it well, and no I wasn't born that way.

      The language style didn't come across to me as patronising but rather easy-going and laid back-- the same style I see in the Camel book, actually. It's friendly, straight-forward and yes, is written for people like me who were not born with programming genes. Nice beginning tutorial, Brian. Keep writing them.
A reply falls below the community's threshold of quality. You may see it by logging in.