100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Your First Perl Script

A hands-on walkthrough of structuring, running, and debugging a complete beginner Perl script that reads, processes, and prints data.

FoundationsBeginner10 min readJul 10, 2026
Analogies

Your First Perl Script

Writing a first real Perl script means combining what a beginner has already learned, the shebang line, use strict; use warnings;, scalars, arrays, hashes, and operators, into a small program that actually does something useful, such as reading a list of names from a file and printing a personalized greeting for each one. A well-structured script separates concerns even at a small scale: input handling (opening and reading a file or STDIN) is kept distinct from processing logic (looping and transforming the data) and from output (printing results), which makes the script easier to debug and to later split into subroutines as it grows. Every Perl file that will be reused as a module rather than run directly should end with a true value, conventionally the literal 1;, but a standalone executable script does not need this.

🏏

Cricket analogy: Similar to how a match is cleanly divided into distinct phases, the toss, the innings, and the presentation ceremony, a well-structured Perl script separates input, processing, and output into clearly distinct stages.

Reading Input and Printing Output

Perl reads from files with the three-argument form of open, open(my $fh, '<', $filename) or die "Cannot open $filename: $!";, where $! holds the operating system's error message if the open fails, and reading STDIN interactively works the same way using the special filehandle <STDIN>, so my $name = <STDIN>; chomp $name; reads one line and chomp strips the trailing newline character that <STDIN> leaves attached. Output is produced with print, which writes exactly what you give it with no added formatting, or with printf, which works like C's printf and lets you control numeric precision and column width, for example printf("%-10s %5.2f\n", $name, $price); left-aligns a name in a 10-character field and right-aligns a price to two decimal places in a 5-character field.

🏏

Cricket analogy: Similar to how a commentator reads the live scoreboard feed and then formats it into a clean on-screen graphic, <STDIN> reads raw input and printf formats it cleanly, like padding a batter's name to a fixed column width.

Running and Debugging

Run your script with perl script.pl first (or ./script.pl after chmod +x on Unix-like systems), and if it fails, Perl's error messages usually name the exact line number, such as 'Global symbol "$total" requires explicit package name at script.pl line 12,' which almost always means use strict; caught a variable you forgot to declare with my. For deeper debugging, running perl -d script.pl launches Perl's interactive built-in debugger, where commands like n step to the next line, s step into a subroutine call, and p $variable print a variable's current value; alternatively perl -c script.pl performs a syntax-only check without actually running the script, which is a fast way to catch typos before execution. The Data::Dumper core module is invaluable once your script grows beyond simple scalars, since print Dumper(\%hash); pretty-prints the full structure of a complex nested hash or array reference that a plain print statement could not display usefully.

🏏

Cricket analogy: Similar to how DRS reviews a decision ball by ball rather than re-watching the whole innings, perl -d lets you step through a script line by line (n) instead of re-running the whole thing to find a bug.

perl
#!/usr/bin/env perl
use strict;
use warnings;

my $filename = 'names.txt';
open(my $fh, '<', $filename) or die "Cannot open $filename: $!";

my @greetings;
while (my $line = <$fh>) {
    chomp $line;
    next unless length $line;          # skip blank lines
    push @greetings, "Hello, $line! Welcome to Perl.";
}
close($fh);

for my $greeting (@greetings) {
    printf("%-40s [%d chars]\n", $greeting, length($greeting));
}

print "\nProcessed " . scalar(@greetings) . " name(s).\n";

perl -c script.pl is the fastest sanity check in your workflow: it parses the script and reports syntax errors, such as a missing semicolon or an unbalanced brace, without actually executing any of the code, which is especially useful before running a script that has side effects like deleting files.

  • A well-structured first script separates input handling, processing logic, and output into distinct, readable sections.
  • Use the three-argument open(my $fh, '<', $filename) or die "...: $!"; idiom to read files safely and report failures clearly.
  • <STDIN> reads a line of interactive input, and chomp should be used immediately to strip the trailing newline.
  • printf gives precise control over field width and numeric precision that plain print does not offer.
  • perl -c script.pl performs a fast syntax-only check; perl -d script.pl launches the interactive line-by-line debugger.
  • Perl's error messages report the exact failing line number, and most 'requires explicit package name' errors mean a missing my.
  • Data::Dumper's Dumper() function pretty-prints complex nested data structures that a plain print cannot display usefully.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#PerlStudyNotes#YourFirstPerlScript#Perl#Script#Reading#Input#StudyNotes#SkillVeris#ExamPrep