# -*- perl -*- # hello world # print a simple string on stdout print "Hello World\n" # argv # access command line parameters (no segmentation fault accepted, nor silent exception, so some languages must explicitly check the presence of the argument) print "$ARGV[0]\n" # env # access environment variable print "$ENV{HOME}\n" # test file exists # return exit code error (non zero) if a file does not exist -e "/etc/mtab" or exit 1 # test file readable # return exit code error (non zero) if a file is not readable -r "/etc/mtab" or exit 1 # formatting # print integers in a simple formatted string $a=1; $b=2; print "$a + $b = ", $a + $b, "\n" # system # call an external program and check the return value system "false" and warn "false failed\n"; system "echo done" # sed in place # remove #-comments from a file (modifying the file, i.e. in place) % perl -pi -e "s/#.*//" # compile what must be # find and compile .c files into .o when the .o is old or absent use File::Find; find({ no_chdir => 1, wanted => sub { if (($o = $_) =~ s/\.c$/.o/ && -M $_ <= -M $o) { print "compiling $_ to $o\n"; system qw(gcc -c -o), $o, $_; } } }, '.'); # grep # grep with -F -i -h handling, usage, grep'ing many files use Getopt::Std; getopts('Fih', \%h); !@ARGV || $h{h} and die "usage: grep [-F] [-i] regexp [files...]\n"; $r = ($h{i} && '(?i)') . shift; $r = "\Q$r" if $h{F}; $prefix = @ARGV > 1; while (<>) { print $prefix && "$ARGV:", $_ if /$r/o; }