How to get Perl to loop over all files in a directory?
bash, linux, perl
Solution
Yes.
The `for f in ...;` translates to the Perl
- `for my $f (...) { ... }` (in the case of lists) or
- `while (my $f = ...) { ... }` (in the case of iterators).
The glob expression that you use (`/etc/puppet/nodes/*.pp`) can be evaluated inside Perl via the `glob` function: `glob '/etc/puppet/nodes/*.pp'`.
Together with some style improvements:
use strict; use warnings;
use autodie; # automatic error handling
while (defined(my $file = glob '/etc/puppet/nodes/*.pp')) {
open my $fh, "<", $file; # lexical file handles, automatic error handling
while (defined( my $line = <$fh> )) {
do stuff;
}
close $fh;
}
Then:
$ /etc/puppet/nodes/brackets.pl
Problem
I have a Perl script with contains ``` open (FILE, '<', "$ARGV[0]") || die "Unable to open $ARGV[0]\n"; while (defined (my $line = <FILE>)) { # do stuff } close FILE; ``` and I would like to run this script on all `.pp` files in a directory, so I have written a wrapper script in Bash ``` #!/bin/bash for f in /etc/puppet/nodes/*.pp; do /etc/puppet/nodes/brackets.pl $f done ``` Question Is it possible to avoid the wrapper script and have the Perl script do it instead?