B
Brian Greenfield
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
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