Reputation:
My question as follows:
I struck with how to pass the command line arguments instead of passing directory path using perl .
Example suppose if am executing the file as follows:
./welcome.pl -output_dir "/home/data/output"
My code:
#!/usr/local/bin/perl
use strict;
use warnings 'all';
use Getopt::Long 'GetOptions';
GetOptions(
'output=s' => \my $output_dir,
);
my $location_dir="/home/data/output";
print $location_dir;
Code explanation:
I tried to print the contents in the $output_dir.so i need to pass the command line arguments inside the variable (i.e $location_dir
) instead of passing path directly how can i do it?
Upvotes: 0
Views: 2608
Reputation: 386696
use strict;
use warnings 'all';
use File::Basename qw( basename );
use Getopt::Long qw( GetOptions );
sub usage {
if (@_) {
my ($msg) = @_;
chomp($msg);
print(STDERR "$msg\n");
}
my $prog = basename($0);
print(STDERR "$prog --help for usage\n");
exit(1);
}
sub help {
my $prog = basename($0);
print(STDERR "$prog [options] --output output_dir\n");
print(STDERR "$prog --help\n");
exit(0);
}
Getopt::Long::Configure(qw( posix_default )); # Optional, but makes the argument-handling consistent with other programs.
GetOptions(
'help|h|?' => \&help,
'output=s' => \my $location_dir,
)
or usage();
defined($location_dir)
or usage("--output option is required\n");
print("$location_dir\n");
Or course, if the argument is indeed required, then why not just use ./welcome.pl "/home/data/output"
instead of an not-really optional parameter.
use strict;
use warnings 'all';
use File::Basename qw( basename );
use Getopt::Long qw( GetOptions );
sub usage {
if (@_) {
my ($msg) = @_;
chomp($msg);
print(STDERR "$msg\n");
}
my $prog = basename($0);
print(STDERR "$prog --help for usage\n");
exit(1);
}
sub help {
my $prog = basename($0);
print(STDERR "$prog [options] [--] output_dir\n");
print(STDERR "$prog --help\n");
exit(0);
}
Getopt::Long::Configure(qw( posix_default )); # Optional, but makes the argument-handling consistent with other programs.
GetOptions(
'help|h|?' => \&help,
)
or usage();
@ARGV == 1
or usage("Incorrect number of arguments\n");
my ($location_dir) = @ARGV;
print("$location_dir\n");
Upvotes: 2