2017-03-06 3 views
0

Meine Frage:Wie übergeben Sie den Verzeichnispfad als Argumente über die Kommandozeile mit Perl? wie folgt

ich mit schlug wie Argumente die Befehlszeilenverzeichnispfad zu übergeben, statt mit perl übergeben.

Beispiel nehme an, wenn die Datei bin Ausführung wie folgt:

./welcome.pl -output_dir "/home/data/output" 

Mein 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 Erklärung:

Ich habe versucht, den Inhalt in der $ output_dir.so drucken Ich muss die Kommandozeilenargumente innerhalb der Variablen übergeben (zB $location_dir) anstatt Pfad direkt zu übergeben, wie kann ich es tun?

Antwort

1
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"); 

Oder natürlich, wenn das Argument tatsächlich erforderlich ist, dann warum ./welcome.pl "/home/data/output" einfach nicht statt einem optionalen Parameter nicht-wirklich nutzen.

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"); 
+0

Können Sie mir erklären, warum Sie Hilfe-Option verwendet @ikegami –

+0

musste nicht. Aber ich fühlte, dass es besser war, als 'print (STDERR) zu setzen. Fragen Sie den Benutzer" find data "auf StackOverflow für die Verwendung \ n"); 'in' usage() ':) – ikegami

+0

Vielen Dank für Ihre Antwort –

Verwandte Themen