Forcing list context

From: Brian Greenfield (not-for-replies_at_zombie.org.uk)
Date: 12/31/03


Date: Wed, 31 Dec 2003 12:02:27 GMT

I was writing a script that needed to find the free space on a mounted
Linux partition (mounted on /backup) and I wrote the following
snippet:

    my @res = split /\s+/, grep m{/backup}, `df`; # 1

The problem being that the second argument of split is evaluated in
scalar context so grep returns the number of matches instead of the
actual match (there will only ever be a single match). I got round
this problem by inserting a join so that grep is evaluated in list
context:

    my @res = split /\s+/, join '', (grep m{/backup}, `df`); # 2

While this works, it seems a little kludgey. I know I could have
indexed grep's list result:

    my @res = split /\s+/, (grep m{/backup}, `df`)[0]; # 3

I intended to go on to do a list splice to get the fields I wanted
(the second to fourth) and I wanted to avoid the using indexing twice:

    my @res = (split /\s+/, (grep m{/backup}, `df`)[0])[1..3]; # 4

I ended up using the splice with method 2:

    my @res = (split /\s+/,
      join '', (grep m{/backup}, `df`))[1..3]; # 5

Does Perl offer any other ways of forcing list context?

Sample output from df, for reference

Filesystem 1K-blocks Used Available Use% Mounted on
/dev/hdb2 29300456 20002976 7809060 72% /backups
/dev/hdc1 12998064 3069480 9268316 25% /mirrors



Relevant Pages

  • Re: Forcing list context
    ... > scalar context so grep returns the number of matches instead of the ... > actual match (there will only ever be a single match). ... > I intended to go on to do a list splice to get the fields I wanted ... > Does Perl offer any other ways of forcing list context? ...
    (comp.lang.perl.misc)
  • Re: Forcing list context
    ... > scalar context so grep returns the number of matches instead of the ... > I intended to go on to do a list splice to get the fields I wanted ...
    (comp.lang.perl.misc)
  • Re: Is Perl still worth learning?
    ... the internal behavior of a function changes depending on whether you assign its return value into a scalar or an array. ... It depends on whether you evaluate the function a list context ... Getting back to Perl and its notion of scalar vs. list context, ... For example, in Perl, there is a "grep" function. ...
    (comp.programming)
  • Re: FAQ 6.21 Whats wrong with using grep in a void context?
    ... The problem is that grep builds a return list, ... map suffers from this problem as ... But since 5.8.1, this has been fixed, and map is context ... no lists are constructed. ...
    (comp.lang.perl.misc)
  • Re: FAQ 6.21 Whats wrong with using grep in a void context?
    ... The problem is that grep builds a return list, ... map suffers from this problem as well. ... But since 5.8.1, this has been fixed, and map is context aware - ... in void context, no lists are constructed. ...
    (comp.lang.perl.misc)