Perl beginner

How to Run Perl Code on macOS (Terminal, Scripts, Shebangs, Modules, and Common Pitfalls)

Question

how to run a perl code in mac

Metadata

  • Category: Perl
  • Difficulty: Beginner
  • Tags: perl, macos, terminal, shebang, homebrew, cpan, modules, permissions

Overview

Running Perl on a Mac is usually straightforward: you write a .pl file (or use a one-liner), then execute it with the perl interpreter from the Terminal. The main things that trip people up are (1) which Perl you’re using (Apple’s system Perl vs a Homebrew/perlbrew Perl), (2) file permissions and the “shebang” line (#!/usr/bin/env perl), (3) missing modules, and (4) PATH issues.

This guide covers: checking if Perl exists on your Mac, several ways to run Perl code, how to make scripts executable, how to install and use modules safely, best practices for writing scripts, and common pitfalls with fixes. It includes runnable code examples with expected output.

1) Check whether Perl is installed

Open Terminal (Spotlight Search → “Terminal”), then run:

perl -v
which perl
perl -e 'print "Perl works!\n"'

What to expect:

  • perl -v prints the Perl version and copyright info.
  • which perl shows the path to the Perl executable being used (for example, /usr/bin/perl for the system Perl, or something like /opt/homebrew/bin/perl if you installed one via Homebrew).
  • The one-liner prints Perl works!.

Note: Apple has historically shipped Perl with macOS, but it has also warned that some scripting runtimes may be deprecated/removed in future macOS releases. If your Mac doesn’t have Perl, or if you want a newer/isolated Perl for development, install your own Perl (see the installation section below).

2) The simplest way: run a script with perl yourscript.pl

Create a file (for example, hello.pl) using any text editor (VS Code, BBEdit, nano, etc.). Here’s a minimal, good-quality Perl script skeleton:

use strict;
use warnings;
use feature 'say';

say "Hello from Perl on macOS!";

Run it from the directory where the file lives:

perl hello.pl

That’s the most portable and least confusing method, because it explicitly uses the Perl interpreter you are calling (as resolved by your PATH).

3) Run Perl code without a file (one-liners)

Perl is excellent for quick command-line tasks:

perl -e 'print "hi\n"'
perl -E 'say 2 + 2'
  • -e runs code from the command line.
  • -E enables more modern conveniences (like say) without extra boilerplate.

4) Make a Perl script executable (shebang + chmod)

If you want to run your script like a normal command (for example, ./myscript), do this:

  1. Add a shebang line as the first line of the file.
  2. Make the file executable via chmod +x.

Recommended shebang:

#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';

say "I am executable.";

Then:

chmod +x myscript.pl
./myscript.pl

Why /usr/bin/env perl? It uses whatever perl is first in your PATH. This is helpful if you install your own Perl (Homebrew/perlbrew) and want scripts to use that Perl automatically. If you hardcode #!/usr/bin/perl, you force the system Perl even when you intended to use your project Perl.

5) Installing a newer Perl (recommended for development)

There are three common approaches on macOS:

A) Use the system Perl

  • Pros: already there (often), no setup.
  • Cons: may be older; Apple may change/remove it; installing modules globally can be painful and discouraged.

B) Install Perl via Homebrew

This gives you a user-managed Perl and a saner place for modules. Typical steps:

brew install perl
which perl
perl -v

If after installation which perl still points to /usr/bin/perl, you likely need to ensure Homebrew’s bin directory is earlier in PATH (Apple Silicon commonly uses /opt/homebrew/bin; Intel commonly uses /usr/local/bin).

C) Use perlbrew (best for multiple Perls)

  • Pros: install multiple Perl versions per user, switch per project, very common in Perl communities.
  • Cons: slightly more setup, but worth it for serious work.

Once you have your own Perl, you can keep project dependencies isolated and avoid breaking system tooling.

6) Installing modules (CPAN) the safe way

A classic beginner problem is: “My script says it can’t find module X.” On macOS you should avoid installing CPAN modules into the system Perl globally (permissions and OS integrity protections can get in the way, and it can cause maintenance headaches).

Better options:

  • Use Homebrew Perl and install modules for that Perl.
  • Use local::lib to install modules into your home directory.
  • Use cpanm (App::cpanminus) for simpler installs.

Example workflow with a user-local module directory:

perl -Mlocal::lib
# If local::lib is missing, install it with your chosen Perl toolchain.

# Then install modules to your home (example):
cpanm --local-lib=~/perl5 Some::Module

In Perl scripts, you generally do not need to hardcode library paths if your environment is configured correctly. The goal is: reproducible installs per user or per project.

7) Runnable Perl Examples (with expected output)

Example 1: Run a Perl script file with arguments

File: hello_args.pl

use strict;
use warnings;
use feature 'say';

my $name = $ARGV[0] // 'World';

say "Hello, $name!";
say "Args: " . scalar(@ARGV);

Run:

perl hello_args.pl Mac

Expected output:

Hello, Mac!
Args: 1

What this demonstrates:

  • How to run a script file.
  • How to read command-line arguments via @ARGV.
  • Why use strict; use warnings; is a best practice (it catches many mistakes early).

Example 2: Read from STDIN (piping input) and compute a sum

File: stdin_sum.pl

use strict;
use warnings;
use feature 'say';

my @nums;
while (my $line = <STDIN>) {
  chomp $line;
  next if $line =~ /^\s*$/;
  push @nums, 0 + $line;
}

my $sum = 0;
$sum += $_ for @nums;
my $count = scalar @nums;
my $avg = $count ? ($sum / $count) : 0;

say "Sum: $sum";
say "Count: $count";
say sprintf("Avg: %.2f", $avg);

Run (pipe three numbers into the script):

printf "10\n20\n30\n" | perl stdin_sum.pl

Expected output:

Sum: 60
Count: 3
Avg: 20.00

What this demonstrates:

  • Using Perl as a command-line filter (very common on macOS).
  • Reading from STDIN with <STDIN>.
  • Basic numeric conversion and formatting.

Example 3: Use a core module (Digest::SHA) for a deterministic result

File: sha256.pl

use strict;
use warnings;
use feature 'say';
use Digest::SHA qw(sha256_hex);

my $text = "hello";
my $hash = sha256_hex($text);

say $hash;

Run:

perl sha256.pl

Expected output:

2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

What this demonstrates:

  • How to use a module.
  • How to run code that depends on module availability.
  • A stable expected output (useful for sanity checks and automation).

8) Best practices for running Perl on macOS

  • Always use strict and warnings: Start scripts with use strict; use warnings; to catch typos and logic errors early.
  • Use perl -c to syntax-check: perl -c yourscript.pl checks syntax without running the script body.
  • Prefer a user-managed Perl for projects: Homebrew Perl or perlbrew reduces friction and avoids system-level surprises.
  • Pin dependencies per project: Use a local module install strategy (local::lib, cpanfile/Carton, or perlbrew + local libs) so scripts work the same later.
  • Keep scripts portable: Use #!/usr/bin/env perl and avoid macOS-specific paths unless you truly need them.
  • Handle UTF-8 intentionally: If you process non-ASCII text, declare and manage encoding explicitly (input/output layers), rather than assuming defaults.

9) Common pitfalls (and how to fix them)

Pitfall: “Permission denied” when running ./script.pl

  • Fix: chmod +x script.pl, and ensure the first line is a valid shebang.
  • Also verify you are in the correct directory: pwd, ls.

Pitfall: “bad interpreter: /usr/bin/perl: no such file or directory”

  • This usually means your shebang points to a Perl that doesn’t exist.
  • Fix: use #!/usr/bin/env perl or update the shebang to your actual Perl path (check with which perl).

Pitfall: Wrong Perl (system Perl vs Homebrew Perl)

  • Symptom: Modules appear “missing” even after you installed them (you installed them for a different Perl).
  • Fix: confirm which Perl runs your script: which perl, then install modules using that Perl’s toolchain.

Pitfall: “Can’t locate Some/Module.pm in @INC”

  • Meaning: Perl can’t find the module in its library search paths.
  • Fix: install the module for the Perl you’re using, or configure a local library (don’t hack @INC unless you understand why).

Pitfall: Script edited with Windows line endings (CRLF)

  • Symptom: weird errors, especially with shebang lines.
  • Fix: convert the file to Unix line endings (many editors can do this; command-line tools like dos2unix also help).

Pitfall: Running from Finder/Double-click

  • Double-clicking a .pl file may open it in an editor instead of running it, and environment variables (like PATH) may differ.
  • Fix: run scripts from Terminal, or wrap them in an app/bundle if you truly need a GUI launch.

10) A practical “daily workflow” on macOS

  1. Write code in an editor (VS Code is common).
  2. Open Terminal to your project folder: cd ~/path/to/project.
  3. Run perl -c script.pl to quickly check syntax.
  4. Run perl script.pl (or ./script.pl if executable).
  5. If you need dependencies, install them into a project/user-local environment, not the OS Perl.

If you follow the above, you’ll have a reliable and repeatable way to run Perl code on a Mac, whether for small command-line tasks or larger projects.

Verified Code

Executed in a sandbox to capture real output. • 6ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Hello, World!
Args: 0
STDERR
(empty)

Was this helpful?

Related Questions