开发者

Best way to check if argument is a filename or a file containing a list of filenames?

开发者 https://www.devze.com 2023-03-30 18:14 出处:网络
I\'m writing a Perl script, and I\'d like a way to have the user enter a file or a file containing a list of files in $ARGV[0].

I'm writing a Perl script, and I'd like a way to have the user enter a file or a file containing a list of files in $ARGV[0].

The current way that I'm doing it is to ch开发者_StackOverflow中文版eck if the filename starts with an @, if it does, then I treat that file as a list of filenames.

This is definitely not the ideal way to do it, because I've noticed that @ is a special character in bash (What does it do by the way? I've only seen it used in $@ in bash).


You can specify additional parameter on your command line to treat it differenly e.g.

perl script.pl file

for reading file's content, or

perl script.pl -l file

for reading list of files from file.

You can use getopt module for easier parsing of input arguments.


First, you could use your shell to grab the list for you:

perl script.pl <( cat list )

If you don't want to do that, perhaps because you are running against the maximum command line length, you could use the following before you use @ARGV or ARGV (including <>):

@ARGV = map {
   if (my $qfn = /^\@(.*)/s) {
      if (!open(my $fh, '<', $qfn)) {
          chomp( my @args = <$fh> );
          @args
      } else {
          warn("Can't open $qfn: $!\n");
          ()
      }
   } else {
      $_
   }
} @ARGV;

Keep in mind that you'll have unintended side effects if you have a file whose name starts with "@".


'@' is special in Perl, so you need to escape it in your Perl strings--unless you use the non-interpolating string types of 'a non-interpolating $string' or q(another non-interpolating $string) or you need to escape it, like so

if ( $arg =~ /^\@/ ) {
    ...
}

Interpolating delimiters are any of the following:

  • "..." or qq/.../
  • `...` or qx/.../
  • /.../ or qr/.../

For all those, you will have to escape any literal @.

Otherwise, a filename starting with a @ has pretty good precedence in command line arguments.

0

精彩评论

暂无评论...
验证码 换一张
取 消