perlfaq7(3)

πŸ“¦
version 5.20250619 Β· 4 versions
, in fedora 43

πŸ’– perlfaq7(3) β€” General Perl Language Issues πŸ’–

okay bestie, this page is from the User Contributed Perl Documentation, and it's giving general Perl language issues energy. no cap, let's go. 🫢


✨ NAME ✨

perlfaq7 - General Perl Language Issues

🌸 VERSION 🌸

version 5.20250619

πŸ¦‹ DESCRIPTION πŸ¦‹

This section deals with general Perl language issues that don't clearly fit into any of the other sections.


✨ Can I get a BNF/yacc/RE for the Perl language? ✨

There is no BNF, bestie. but you can paw your way through the yacc grammar in perly.y in the source distribution if you're particularly brave. The grammar relies on very smart tokenizing code, so be prepared to venture into toke.c as well.

In the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF. The work of parsing perl is distributed between yacc, the lexer, smoke and mirrors."


πŸ’… What are all these $@%&* punctuation signs, and how do I know when to use them? πŸ’…

They are type specifiers, as detailed in perldata:

$ for scalar values (number, string or reference)
@ for arrays
% for hashes (associative arrays)
& for subroutines (aka functions, procedures, methods)
* for all types of that symbol name. In version 4 you used them like
  pointers, but in modern perls you can just use references.

There are a couple of other symbols that you're likely to encounter that aren't really type specifiers:

<> are used for inputting a record from a filehandle.
\  takes a reference to something.

Note that <FILE> is neither the type specifier for files nor the name of the handle. It is the <> operator applied to the handle FILE. It reads one line (well, record--see $/ in perlvar) from the handle FILE in scalar context, or all lines in list context. When performing open, close, or any other operation besides <> on files, or even when talking about the handle, do not use the brackets. These are correct: eof(FH), "seek(FH, 0, 2)" and "copying from STDIN to FILE".


πŸŽ€ Do I always/never have to quote my strings or use semicolons and commas? πŸŽ€

Normally, a bareword doesn't need to be quoted, but in most cases probably should be (and must be under use strict). But a hash key consisting of a simple word and the left-hand operand to the => operator both count as though they were quoted:

This                    is like this
------------            ---------------
$foo{line}              $foo{'line'}
bar => stuff            'bar' => stuff

The final semicolon in a block is optional, as is the final comma in a list. Good style (see perlstyle) says to put them in except for one-liners:

if ($whoops) { exit 1 }
my @nums = (1, 2, 3);

if ($whoops) {
    exit 1;
}

my @lines = (
    "There Beren came from mountains cold",
    "And lost he wandered under leaves",
);

🌈 How do I skip some return values? 🌈

One way is to treat the return values as a list and index into it:

$dir = (getpwnam($user))[7];

Another way is to use undef as an element on the left-hand-side:

($dev, $ino, undef, undef, $uid, $gid) = stat($file);

You can also use a list slice to select only the elements that you need:

($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];

🧚 How do I temporarily block warnings? 🧚

If you are running Perl 5.6.0 or better, the use warnings pragma allows fine control of what warnings are produced. See perllexwarn for more details.

{
    no warnings;          # temporarily turn off warnings
    $x = $y + $z;         # I know these might be undef
}

Additionally, you can enable and disable categories of warnings. You turn off the categories you want to ignore and you can still get other categories of warnings. See perllexwarn for the complete details, including the category names and hierarchy.

{
    no warnings 'uninitialized';
    $x = $y + $z;
}

If you have an older version of Perl, the $^W variable (documented in perlvar) controls runtime warnings for a block:

{
    local $^W = 0;        # temporarily turn off warnings
    $x = $y + $z;         # I know these might be undef
}

Note that like all the punctuation variables, you cannot currently use my() on $^W, only local().


🌸 What's an extension? 🌸

An extension is a way of calling compiled C code from Perl. Reading perlxstut is a good place to learn more about extensions.


πŸ”₯ Why do Perl operators have different precedence than C operators? πŸ”₯

Actually, they don't. All C operators that Perl copies have the same precedence in Perl as they do in C. The problem is with operators that C doesn't have, especially functions that give a list context to everything on their right, eg. print, chmod, exec, and so on. Such functions are called "list operators" and appear as such in the precedence table in perlop.

A common mistake is to write:

unlink $file || die "snafu";

This gets interpreted as:

unlink ($file || die "snafu");

To avoid this problem, either put in extra parentheses or use the super low precedence or operator:

(unlink $file) || die "snafu";
unlink $file or die "snafu";

The "English" operators (and, or, xor, and not) deliberately have precedence lower than that of list operators for just such situations as the one above.

Another operator with surprising precedence is exponentiation. It binds more tightly even than unary minus, making -2**2 produce a negative four and not a positive one. It is also right-associating, meaning that 2**3**2 is two raised to the ninth power, not eight squared.

Although it has the same precedence as in C, Perl's ?: operator produces an lvalue. This assigns $x to either $if_true or $if_false, depending on the trueness of $maybe:

($maybe ? $if_true : $if_false) = $x;

πŸ’œ How do I declare/create a structure? πŸ’œ

In general, you don't "declare" a structure. Just use a (probably anonymous) hash reference. See perlref and perldsc for details. Here's an example:

$person = {};                   # new anonymous hash
$person->{AGE}  = 24;           # set field AGE to 24
$person->{NAME} = "Nat";        # set field NAME to "Nat"

If you're looking for something a bit more rigorous, try perlootut.


πŸŽ€ How do I create a module? πŸŽ€

perlnewmod is a good place to start, ignore the bits about uploading to CPAN if you don't want to make your module publicly available.

ExtUtils::ModuleMaker and Module::Starter are also good places to start. Many CPAN authors now use Dist::Zilla to automate as much as possible.

Detailed documentation about modules can be found at: perlmod, perlmodlib, perlmodstyle.

If you need to include C code or C library interfaces use h2xs. h2xs will create the module distribution structure and the initial interface files. perlxs and perlxstut explain the details.


✨ How do I adopt or take over a module already on CPAN? ✨

Ask the current maintainer to make you a co-maintainer or transfer the module to you.

If you can not reach the author for some reason contact the PAUSE admins at modules@perl.org who may be able to help, but each case is treated separately.

  • Get a login for the Perl Authors Upload Server (PAUSE) if you don't already have one: <http://pause.perl.org>
  • Write to modules@perl.org explaining what you did to contact the current maintainer. The PAUSE admins will also try to reach the maintainer.
  • Post a public message in a heavily trafficked site announcing your intention to take over the module.
  • Wait a bit. The PAUSE admins don't want to act too quickly in case the current maintainer is on holiday. If there's no response to private communication or the public post, a PAUSE admin can transfer it to you.

πŸ’… How do I create a class? πŸ’…

(contributed by brian d foy)

In Perl, a class is just a package, and methods are just subroutines. Perl doesn't get more formal than that and lets you set up the package just the way that you like it (that is, it doesn't set up anything for you).

See also perlootut, a tutorial that covers class creation, and perlobj.


πŸ¦‹ How can I tell if a variable is tainted? πŸ¦‹

You can use the tainted() function of the Scalar::Util module, available from CPAN (or included with Perl since release 5.8.0). See also "Laundering and Detecting Tainted Data" in perlsec.


🌸 What's a closure? 🌸

Closures are documented in perlref.

Closure is a computer science term with a precise but hard-to-explain meaning. Usually, closures are implemented in Perl as anonymous subroutines with lasting references to lexical variables outside their own scopes. These lexicals magically refer to the variables that were around when the subroutine was defined (deep binding).

Closures are most often used in programming languages where you can have the return value of a function be itself a function, as you can in Perl. Note that some languages provide anonymous functions but are not capable of providing proper closures: for example Python 2. For more information on closures, check out any textbook on functional programming. Scheme is a language that not only supports but encourages closures.

Here's a classic non-closure function-generating function:

sub add_function_generator {
    return sub { shift() + shift() };
}

my $add_sub = add_function_generator();
my $sum = $add_sub->(4,5);                # $sum is 9 now.

The anonymous subroutine returned by add_function_generator() isn't technically a closure because it refers to no lexicals outside its own scope. Using a closure gives you a function template with some customization slots left out to be filled later.

Contrast this with the following make_adder() function, in which the returned anonymous function contains a reference to a lexical variable outside the scope of that function itself. Such a reference requires that Perl return a proper closure, thus locking in for all time the value that the lexical had when the function was created.

sub make_adder {
    my $addpiece = shift;
    return sub { shift() + $addpiece };
}

my $f1 = make_adder(20);
my $f2 = make_adder(555);

Now $f1->($n) is always 20 plus whatever $n you pass in, whereas $f2->($n) is always 555 plus whatever $n you pass in. The $addpiece in the closure sticks around.

Closures are often used for less esoteric purposes. For example, when you want to pass in a bit of code into a function:

my $line;
timeout( 30, sub { $line = <STDIN> } );

If the code to execute had been passed in as a string, '$line = <STDIN>', there would have been no way for the hypothetical timeout() function to access the lexical variable $line back in its caller's scope.

okay so like, another iconic use for closures? πŸ’… making a variable that's private to a named subroutine. think: a counter that gets initialized the moment the sub is created, and can only be modified from inside the sub itself. no outside hands, no meddling. people do this with a BEGIN block in package files to keep a variable safe and untouched for the whole lifetime of the package:

BEGIN {
    my $id = 0;
    sub next_id { ++$id }
}

There's more tea on this in perlsub β€” go read the entry on Persistent Private Variables. 🫢

🩹 What is variable suicide and how can I prevent it?

okay bestie, first things first: this problem was fixed in perl 5.004_05, so preventing it means... upgrading your perl. ;) that's it. that's the prevention.

so what is variable suicide? it's when you (temporarily or permanently) lose the value of a variable. 😭 the cause is scoping β€” my() and local() getting tangled up with either closures or aliased foreach() iterator variables and subroutine arguments. it used to be super easy to accidentally lose a variable's value this way, but now it's way harder. look at this:

my $f = 'foo';
sub T {
    while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
}

T;
print "Finally $f\n";

if you're experiencing variable suicide, that my $f inside the subroutine does not pick up a fresh copy of the $f whose value is 'foo'. and the output proves it β€” inside the sub, the value of $f leaks through when it should not:

foobar
foobarbar
foobarbarbar
Finally foo

the $f that got "bar" added to it three times should be a brand new $f. my $f is supposed to create a new lexical variable every single time through the loop. the expected output is:

foobar
foobar
foobar
Finally foo

πŸ“¦ How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?

bestie, the answer is references. you need to pass references to these objects. for this particular question, see "Pass by Reference" in perlsub, and for everything reference-related, see perlref.

Passing Variables and Functions

regular variables and functions? so easy. just pass in a reference to an existing or anonymous variable or function:

func( \$some_scalar );

func( \@some_array  );
func( [ 1 .. 10 ]   );

func( \%some_hash   );
func( { this => 10, that => 20 }   );

func( \&some_func   );
func( sub { $_[0] ** $_[1] }   );

Passing Filehandles

as of Perl 5.6, you can represent filehandles with scalar variables, and you just treat them like any other scalar. ✨

open my $fh, $filename or die "Cannot open $filename! $!";
func( $fh );

sub func {
    my $passed_fh = shift;

    my $line = <$passed_fh>;
}

before Perl 5.6, you had to use the *FH or "\*FH" notations. those are "typeglobs" β€” see "Typeglobs and Filehandles" in perldata and especially "Pass by Reference" in perlsub for more info.

Passing Regexes

here's an example of how to pass in a string and a regular expression for it to match against. you construct the pattern with the qr// operator:

sub compare {
    my ($val1, $regex) = @_;
    my $retval = $val1 =~ /$regex/;
    return $retval;
}
$match = compare("old McDonald", qr/d.*D/i);

Passing Methods

to pass an object method into a subroutine, you can do this:

call_a_lot(10, $some_obj, "methname")
sub call_a_lot {
    my ($count, $widget, $trick) = @_;
    for (my $i = 0; $i < $count; $i++) {
        $widget->$trick();
    }
}

or, you can use a closure to bundle up the object, its method call, and its arguments:

my $whatnot = sub { $some_obj->obfuscate(@args) };
func($whatnot);
sub func {
    my $code = shift;
    &$code();
}

you could also go investigate the can() method in the UNIVERSAL class (part of the standard perl distribution). πŸ‘‘


🧊 How do I create a static variable?

(contributed by brian d foy)

in Perl 5.10, you declare the variable with state. the state declaration creates the lexical variable that persists between calls to the subroutine:

sub counter { state $count = 1; $count++ }

you can fake a static variable by using a lexical variable that goes out of scope. in this example, you define the subroutine counter, and it uses the lexical variable $count. since you wrap this in a BEGIN block, $count is defined at compile-time, but it also goes out of scope at the end of the BEGIN block. the BEGIN block also ensures that the subroutine and the value it uses are defined at compile-time, so the subroutine is ready to use just like any other subroutine, and you can put this code in the same place as other subroutines in the program text (i.e. at the end of the code, typically). the subroutine counter still has a reference to the data, and is the only way you can access the value (and each time you do, you increment it). the data in the chunk of memory defined by $count is private to counter.

BEGIN {
    my $count = 1;
    sub counter { $count++ }
}

my $start = counter();

.... # code that calls counter();

my $end = counter();

in the previous example, you created a function-private variable because only one function remembered its reference. but you could define multiple functions while the variable is in scope, and each function can share the "private" variable. it's not really "static" though, because you can access it outside the function while the lexical variable is in scope β€” and even create references to it. in this example, increment_count and return_count share the variable. one function adds to the value and the other simply returns the value. they can both access $count, and since it has gone out of scope, there's no other way to access it.

BEGIN {
    my $count = 1;
    sub increment_count { $count++ }
    sub return_count    { $count }
}

to declare a file-private variable, you still use a lexical variable. a file is also a scope, so a lexical variable defined in the file can't be seen from any other file. πŸŽ€

see "Persistent Private Variables" in perlsub for more information. the discussion of closures in perlref may help you, even though we did not use anonymous subroutines in this answer. see "Persistent Private Variables" in perlsub for details.

πŸ”€ What's the difference between dynamic and lexical (static) scoping? Between local() and my()?

local($x) saves away the old value of the global variable $x and assigns a new value for the duration of the subroutine, which is visible in other functions called from that subroutine. this is done at run-time, so it's called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables.

my($x) creates a new variable that's only visible in the current subroutine. this is done at compile-time, so it's called lexical or static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables.

for instance:

sub visible {
    print "var has value $var\n";
}

sub dynamic {
    local $var = 'local';    # new temporary value for the still-global
    visible();              #   variable called $var
}

sub lexical {
    my $var = 'private';    # new private variable, $var
    visible();              # (invisible outside of sub scope)
}

$var = 'global';

visible();              # prints global
dynamic();              # prints local
lexical();              # prints global

notice how at no point does the value "private" get printed. that's because $var only has that value inside the block of the lexical() function, and it's hidden from the called subroutine. 🫣

in summary: local() does not make what you think of as private, local variables. it gives a global variable a temporary value. my() is what you're looking for if you want private variables. periodt. πŸ’…

see "Private Variables via my()" in perlsub and "Temporary Values via local()" in perlsub for excruciating details.

πŸ•΅οΈ How can I access a dynamic variable while a similarly named lexical is in scope?

if you know your package, you can just mention it explicitly, as in $Some_Pack::var. heads up though: the notation $::var is not the dynamic $var in the current package, but rather the one in the "main" package, as though you had written $main::var.

use vars '$var';
local $var = "global";
my    $var = "lexical";

print "lexical is $var\n";
print "global  is $main::var\n";

alternatively, you can use the compiler directive our() to bring a dynamic variable into the current lexical scope.

require 5.006; # our() did not exist before 5.6
use vars '$var';

local $var = "global";
my $var    = "lexical";

print "lexical is $var\n";

{
    our $var;
    print "global  is $var\n";
}

πŸͺ’ What's the difference between deep and shallow binding?

in deep binding, lexical variables mentioned in anonymous subroutines are the same ones that were in scope when the subroutine was created. in shallow binding, they're whichever variables with the same names happen to be in scope when the subroutine is called. Perl always uses deep binding of lexical variables (i.e. those created with my()). however, dynamic variables (aka global, local, or package variables) are effectively shallowly bound. consider this just one more reason not to use them. πŸ‘€ see the answer to "What's a closure?".

😭 Why doesn't "my($foo) = <$fh>;" work right?

my() and local() give list context to the right hand side of =. the <$fh> read operation, like so many of Perl's functions and operators, can tell which context it was called in and behaves appropriately. in general, the scalar() function can help. this function does nothing to the data itself (contrary to popular myth) β€” it rather tells its argument to behave in whatever its scalar fashion is. if that function doesn't have a defined scalar behavior, then of course this doesn't help you (such as with sort()).

to enforce scalar context in this particular case, however, you need merely omit the parentheses:

local($foo) = <$fh>;        # WRONG
local($foo) = scalar(<$fh>);   # ok
local $foo  = <$fh>;        # right

you should probably be using lexical variables anyway, although the issue is the same here:

my($foo) = <$fh>;    # WRONG
my $foo  = <$fh>;    # right

πŸ’… How do I redefine a builtin function, operator, or method?

okay bestie, first question: why?? genuinely, why do you want to do that? :-) but like, no judgement, here's the tea:

  • Wanna override a predefined function, like open()? Then you literally have to import the new definition from a different module. Full lore in "Overriding Built-in Functions" in perlsub. πŸ‘‘
  • Wanna overload a Perl operator, like + or **? That's the use overload pragma's whole job, documented in overload.
  • Talking about obscuring method calls in parent classes? That's a different vibe entirely β€” see "Overriding methods and method resolution" in perlootut.

πŸ¦‹ What's the difference between calling a function as &foo and foo()?

(contributed by brian d foy β€” ty king)

So when you call a subroutine as &foo with no trailing parentheses, it ignores the prototype of foo and just passes it the current value of the argument list, @_. it's giving "whatever you had, I'm taking it".

Here's the example β€” the bar subroutine calls &foo, and foo prints its arg list:

sub foo { print "Args in foo are: @_\n"; }

sub bar { &foo; }

bar( "a", "b", "c" );

When you call bar with arguments, surprise surprise, foo got the exact same @_:

Args in foo are: a b c

Now β€” call the subroutine with trailing parentheses, with or without arguments, and it does not use the current @_. Watch the plot twist. Add parentheses after the call to foo and the whole program changes:

sub foo { print "Args in foo are: @_\n"; }

sub bar { &foo(); }

bar( "a", "b", "c" );

Now the output shows foo gets nothing from its caller:

Args in foo are:

However, using & in the call still overrides the prototype of foo if there is one. slay:

sub foo ($$$) { print "Args in foo are: @_\n"; }

sub bar_1 { &foo; }
sub bar_2 { &foo(); }
sub bar_3 { foo( $_[0], $_[1], $_[2] ); }
# sub bar_4 { foo(); }
# bar_4 doesn't compile: "Not enough arguments for main::foo at ..."

bar_1( "a", "b", "c" );
# Args in foo are: a b c

bar_2( "a", "b", "c" );
# Args in foo are:

bar_3( "a", "b", "c" );
# Args in foo are: a b c

The main use of the @_ pass-through feature is to write subroutines whose whole personality is "I call other subroutines for you". For further details, see perlsub. πŸ’œ


🌸 How do I create a switch or case statement?

okay so there is a given/when statement in Perl, but bestie... it's experimental and it's getting removed in Perl 5.42. 😭 So maybe don't build your whole life on it. See perlsyn for more details.

The general answer? Use a CPAN module, like Switch::Plain:

use Switch::Plain;
sswitch($variable_holding_a_string) {
    case 'first': { }
    case 'second': { }
    default: { }
}

Or for more complicated comparisons, the classic if-elsif-else:

for ($variable_to_test) {
    if    (/pat1/)  { }     # do something
    elsif (/pat2/)  { }     # do something else
    elsif (/pat3/)  { }     # do something else
    else            { }     # default
}

Here's a simple example of a switch based on pattern matching, lined up all cute so it looks like a switch statement. We're doing a multiway conditional based on the type of reference stored in $whatchamacallit:

SWITCH: for (ref $whatchamacallit) {

    /^$/           && die "not a reference";

    /SCALAR/       && do {
                    print_scalar($$ref);
                    last SWITCH;
                  };

    /ARRAY/        && do {
                    print_array(@$ref);
                    last SWITCH;
                  };

    /HASH/        && do {
                    print_hash(%$ref);
                    last SWITCH;
                  };

    /CODE/        && do {
                    warn "can't print function ref";
                    last SWITCH;
                  };

    # DEFAULT

    warn "User defined type skipped";

}

See perlsyn for other examples in this style. ✨

Sometimes you should switch up the positions of the constant and the variable. For example, let's say you wanted to test which of many answers you were given, but case-insensitively, and you also wanna allow abbreviations. You can use this technique if the strings all start with different characters, or if you want to arrange the matches so one takes precedence over another β€” like how "SEND" has precedence over "STOP" here:

chomp($answer = <>);
if    ("SEND"  =~ /^\Q$answer/i) { print "Action is send\n"  }
elsif ("STOP"  =~ /^\Q$answer/i) { print "Action is stop\n"  }
elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
elsif ("LIST"  =~ /^\Q$answer/i) { print "Action is list\n"  }
elsif ("EDIT"  =~ /^\Q$answer/i) { print "Action is edit\n"  }

A totally different approach: make a hash of function references. obsessed.

my %commands = (
    "happy" => \&joy,
    "sad"   => \&sullen,
    "done"  => sub { die "See ya!" },
    "mad"   => \&angry,
);

print "How are you? ";
chomp($string = <STDIN>);
if ($commands{$string}) {
    $commands{$string}->();
} else {
    print "No such command: $string\n";
}

Starting from Perl 5.8, there's also a source filter module, Switch, that can give you switch and case. But bestie, its use is now discouraged β€” it's not fully compatible with the native switch of Perl 5.10, and because it's implemented as a source filter, it doesn't always work as intended when complex syntax is involved. πŸ™ˆ


πŸŽ€ How can I catch accesses to undefined variables, functions, or methods?

The AUTOLOAD method β€” discussed in "Autoloading" in perlsub β€” lets you capture calls to undefined functions and methods. very main character of it.

And when it comes to undefined variables that would trigger a warning under use warnings, you can just promote that warning to an error:

use warnings FATAL => qw(uninitialized);

πŸ‘‘ Why can't a method included in this same file be found?

Possible reasons, bestie: your inheritance is getting confused, you've misspelled the method name, or the object is of the wrong type. Check out perlootut for details on any of the above. You can also just use print ref($object) to find out which class $object was blessed into. πŸ”

Another possible reason is that you've used the indirect object syntax (eg, find Guru "Samy") on a class name before Perl has seen that such a package exists. The wisest move is to make sure all your packages are defined before you start using them β€” which is automatically handled if you use the use statement instead of require. If not, make sure to use arrow notation instead (eg., Guru->find("Samy")). Object notation is explained in perlobj.

Make sure to read about creating modules in perlmod, and about the perils of indirect objects in "Method Invocation" in perlobj.


🌈 How can I find out my current or calling package?

(contributed by brian d foy)

To find the package you're currently in, use the special literal __PACKAGE__, as documented in perldata. Heads up though: you can only use special literals as separate tokens, so you can't interpolate them into strings the way you can with variables. rude, I know.

my $current_package = __PACKAGE__;
print "I am in package $current_package\n";

If you want to find the package that's calling your code β€” maybe to give better diagnostics, like Carp does β€” use the caller built-in:

sub foo {
    my @args = ...;
    my( $package, $filename, $line ) = caller;

    print "I was called from package $package\n";
};

By default, your program starts in package main, so you will always be in some package. no cap.

This is different from finding out which package an object is blessed into β€” which might not be the current package at all. For that, use blessed from Scalar::Util, which has been part of the Standard Library since Perl 5.8:

use Scalar::Util qw(blessed);
my $object_package = blessed( $object );

Most of the time though, you shouldn't care what package an object is blessed into β€” as long as it claims to inherit from that class:

my $is_right_class = eval { $object->isa( $package ) }; # true or false

And with Perl 5.10 and later, you don't have to check for inheritance to see if an object can handle a role. For that, use DOES, which comes from UNIVERSAL:

my $class_does_it = eval { $object->DOES( $role ) }; # true or false

You can safely replace isa with DOES β€” although the converse is not true. πŸ’…


πŸ’– How can I comment out a large block of Perl code?

(contributed by brian d foy)

The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line, and somewhere where Perl expects a new statement β€” so not in the middle of statements like # comments. You end the comment with =cut, which closes the Pod section:

=pod

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=cut
The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. Because if a Pod parser comes along, your multiline comment is gonna show up in the Pod translation. 😬

A better way hides it from Pod parsers as well. The =begin directive can mark a section for a particular purpose, and if the Pod parser doesn't want to handle it, it just ignores it. Label the comments with comment, and end the comment using =end with the same label. You still need the =cut to get back to Perl code from the Pod comment:

=begin comment

my $object = NotGonnaHappen->new();

ignored_sub();

$wont_be_assigned = 37;

=end comment

=cut

For more info on Pod, check out perlpod and perlpodspec. 🫢


🧚 How do I clear a package?

Use this code, provided by Mark-Jason Dominus:

sub scrub_package {
    no strict 'refs';
    my $pack = shift;
    die "Shouldn't delete main package"
        if $pack eq "" || $pack eq "main";
    my $stash = *{$pack . '::'}{HASH};
    my $name;
    foreach $name (keys %$stash) {
        my $fullname = $pack . '::' . $name;
        # Get rid of everything with that name.
        undef $$fullname;
        undef @$fullname;
        undef %$fullname;
        undef &$fullname;
        undef *$fullname;
    }
}

Or, if you're using a recent release of Perl, you can just use the Symbol::delete_package() function instead. iconic. ✨


πŸ“ How can I use a variable as a variable name?

Beginners often think they want a variable to contain the name of a variable. like...

$fred    = 23;
$varname = "fred";
++$$varname;         # $fred now 24

okay so bestie, this works sometimes, but it is a very bad idea for two reasons. πŸ’€

The first reason is that this technique only works on global variables. That means that if $fred is a lexical variable created with my() in the above example, the code wouldn't work at all: you'd accidentally access the global and skip right over the private lexical altogether. Global variables are bad because they can easily collide accidentally and in general make for non-scalable and confusing code. ✨

Symbolic references are forbidden under the use strict pragma. They are not true references and consequently are not reference-counted or garbage-collected. 🫢

The other reason why using a variable to hold the name of another variable is a bad idea is that the question often stems from a lack of understanding of Perl data structures, particularly hashes. By using symbolic references, you are just using the package's symbol-table hash (like %main::) instead of a user-defined hash. The solution is to use your own hash or a real reference instead. πŸ’…

$USER_VARS{"fred"} = 23;
my $varname = "fred";
$USER_VARS{$varname}++;  # not $$varname++

There we're using the %USER_VARS hash instead of symbolic references. Sometimes this comes up in reading strings from the user with variable references and wanting to expand them to the values of your perl program's variables. This is also a bad idea because it conflates the program-addressable namespace and the user-addressable one. Instead of reading a string and expanding it to the actual contents of your program's own variables:

$str = 'this has a $fred and $barney in it';
$str =~ s/(\$\w+)/$1/eeg;          # need double eval

it would be better to keep a hash around like %USER_VARS and have variable references actually refer to entries in that hash:

$str =~ s/\$(\w+)/$USER_VARS{$1}/g;   # no /e here at all

That's faster, cleaner, and safer than the previous approach. Of course, you don't need to use a dollar sign. You could use your own scheme to make it less confusing, like bracketed percent symbols, etc. 🌸

$str = 'this has a %fred% and %barney% in it';
$str =~ s/%(\w+)%/$USER_VARS{$1}/g;   # no /e here at all

Another reason that folks sometimes think they want a variable to contain the name of a variable is that they don't know how to build proper data structures using hashes. For example, let's say they wanted two hashes in their program: %fred and %barney, and that they wanted to use another scalar variable to refer to those by name. 😭

$name = "fred";
$$name{WIFE} = "wilma";     # set %fred

$name = "barney";
$$name{WIFE} = "betty";    # set %barney

This is still a symbolic reference, and is still saddled with the problems enumerated above. It would be far better to write:

$folks{"fred"}{WIFE}   = "wilma";
$folks{"barney"}{WIFE} = "betty";

And just use a multilevel hash to start with. ✨

The only times that you absolutely must use symbolic references are when you really must refer to the symbol table. This may be because it's something that one can't take a real reference to, such as a format name. Doing so may also be important for method calls, since these always go through the symbol table for resolution. πŸ’…

In those cases, you would turn off strict 'refs' temporarily so you can play around with the symbol table. For example:

@colors = qw(red blue green yellow orange purple violet);
for my $name (@colors) {
    no strict 'refs';  # renege for the block
    *$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
}

All those functions (red(), blue(), green(), etc.) appear to be separate, but the real code in the closure actually was compiled only once. 🧚

So, sometimes you might want to use symbolic references to manipulate the symbol table directly. This doesn't matter for formats, handles, and subroutines, because they are always global--you can't use my() on them. For scalars, arrays, and hashes, though--and usually for subroutines--you probably only want to use hard references. πŸ‘‘

What does "bad interpreter" mean? πŸ’€

(contributed by brian d foy)

The "bad interpreter" message comes from the shell, not perl. The actual message may vary depending on your platform, shell, and locale settings. 🌈

If you see "bad interpreter - no such file or directory", the first line in your perl script (the "shebang" line) does not contain the right path to perl (or any other program capable of running scripts). Sometimes this happens when you move the script from one machine to another and each machine has a different path to perl--/usr/bin/perl versus /usr/local/bin/perl for instance. It may also indicate that the source machine has CRLF line terminators and the destination machine has LF only: the shell tries to find /usr/bin/perl<CR>, but can't. 😭

If you see "bad interpreter: Permission denied", you need to make your script executable. πŸ’…

In either case, you should still be able to run the scripts with perl explicitly:

% perl script.pl

If you get a message like "perl: command not found", perl is not in your PATH, which might also mean that the location of perl is not where you expect it so you need to adjust your shebang line. 🫢

Do I need to recompile XS modules when there is a change in the C library? 🧐

(contributed by Alex Beamish)

If the new version of the C library is ABI-compatible (that's Application Binary Interface compatible) with the version you're upgrading from, and if the shared library version didn't change, no re-compilation should be necessary. ✨

Copyright (c) 1997-2013 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.

This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.

Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. πŸ’–

stay slay, bestie β€” this page is from perl v5.42.0, dated 2025-07-25, and it's perlfaq7(3). πŸ’…βœ¨

πŸ“¦ where this page comes from