Skip to Main Content
Perl Cookbook
book

Perl Cookbook

by Tom Christiansen, Nathan Torkington
August 1998
Intermediate to advanced content levelIntermediate to advanced
800 pages
39h 20m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook

Skipping Selected Return Values

Problem

You have a function that returns many values, but you only care about some of them. The stat function is a classic example: often you only want one value from its long return list (mode, for instance).

Solution

Either assign to a list with undef in some of the slots:

($a, undef, $c) = func();

or else take a slice of the return list, selecting only what you want:

($a, $c) = (func())[0,2];

Discussion

Using dummy temporary variables is wasteful:

($dev,$ino,$DUMMY,$DUMMY,$uid) = stat($filename);

Use undef instead of dummy variables to discard a value:

($dev,$ino,undef,undef,$uid)   = stat($filename);

Or take a slice, selecting just the values you care about:

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

If you want to put an expression into list context and discard all its return values (calling it simply for side effects), as of version 5.004 you can assign to the empty list:

() = some_function();

See Also

The discussion on slices in Chapter 2 of Programming Perl and perlsub (1); Section 3.1

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl Best Practices

Perl Best Practices

Damian Conway
Mastering Perl

Mastering Perl

brian d foy
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington

Publisher Resources

ISBN: 1565922433Supplemental ContentCatalog PageErrata