home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

10.8. Skipping Selected Return Values


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).


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];


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); Recipe 3.1

Previous: 10.7. Passing by Named Parameter Perl Cookbook Next: 10.9. Returning More Than One Array or Hash
10.7. Passing by Named Parameter Book Index 10.9. Returning More Than One Array or Hash

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.