Recipe 10.8 Skipping Selected Return Values

10.8.1 Problem

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

10.8.2 Solution

Either assign to a list that has undef in some positions:

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

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

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

10.8.3 Discussion

Using dummy temporary variables is wasteful; plus it feels artificial and awkward:

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

A nicer style is to use undef instead of dummy variables to discard a value:

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

Or you can take a slice, picking up 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 of its return values (calling it simply for side effects), you can assign this to the empty list:

( ) = some_function( );

This last strategy is rather like a list version of the scalar operator it calls the function in list context, even in a place it wouldn't otherwise do so. You can get just a count of return values this way:

$count = ( ) = some_function( );

or you can call it in list context and make sure it returns some non-zero number of items (which you immediately discard) like this:

if (( ) = some_function( ))  { .... }

If you hadn't assigned to the empty list, the Boolean context of the if test would have called the function in scalar context.

10.8.4 See Also

The section on "List Values and Arrays" in Chapter 2 of Programming Perl and perlsub(1); Recipe 3.1



Perl Cookbook
Perl Cookbook, Second Edition
ISBN: 0596003137
EAN: 2147483647
Year: 2003
Pages: 501

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net