aewhale has asked for the wisdom of the Perl Monks concerning the following question:

I have inheritted a program that is using the du command. I want to modify it so that it does not perform the du on an NFS disk partition. In the bash shell it's simple `grep -c /home /etc/mtab` command, something like this:
if [ `grep /home /etc/mtab | grep -c nfs` -eq 0 ] then Do something else DO something different endif
How do I do this in perl? Perfect! Thank you both!

Replies are listed 'Best First'.
Re: using grep to test a partition
by superfrink (Curate) on Mar 08, 2007 at 05:09 UTC
    One way is pretty much the same:
    #! /usr/bin/perl -w use strict; if ( `grep /home /etc/mtab | grep -c nfs` == 0 ) { print "Do something\n"; } else { print "DO something different\n"; }
    There is nothing wrong with doing that. It does make the script depend on the "grep" program. A different way is like:
    #! /usr/bin/perl -w use strict; # read the file open FH , "<" , "/etc/mtab" or die "can't open file"; my @line_list = <FH>; close FH; # grep out the "/home" lines @line_list = grep { m/\/home/ } @line_list; # search for "nfs" lines @line_list = grep { m/nfs/ } @line_list; if (scalar @line_list == 0) { print "Do something\n"; } else { print "DO something different\n"; }
    I would see if I could replace both "grep"s with just one and also use a "scalar context" to get the number of matches instead of a line list.
    #! /usr/bin/perl -w use strict; # read the file open FH , "<" , "/etc/mtab" or die "can't open file"; my @line_list = <FH>; close FH; # count the number of "/home" "nfs" lines my $match_count = grep { m/ \/home nfs / } @line_list; if ($match_count == 0) { print "Do something\n"; } else { print "DO something different\n"; }
Re: using grep to test a partition
by mreece (Friar) on Mar 08, 2007 at 05:37 UTC
    i love to abuse @ARGV and <>...
    if (grep m{nfs}, grep m{/home}, map <>, local @ARGV=qw{/etc/mtab}) { # ... } else { # ... }

    update: or, perhaps a little more friendly,

    if (local @ARGV=qw(/etc/mtab) and grep /nfs/, grep m{/home}, <>) { # ... } else { # ... }