2016-11-09 2 views
0

Je veux passer des arguments à partir de la ligne de commande, donc j'ai essayé le code suivant mais il y a une erreur?Pourquoi le code suivant montre-t-il une erreur?

use strict; 
use warnings; 
use Getopt::Long qw(GetOptions); 
use Getopt::Std; 
print "raw data:@ARGV\n"; 
my $site=getopts('bangalore','norwood','limerick'); 
if($site) 
{ 
print "success"; 
} 
else 
{ 
die "error"; 
} 
print "final data:@ARGV \n"; 
+0

getopt, getopts - un seul caractère de processus commute avec le regroupement de commutation. – ssr1012

+0

[Refer] (http://perldoc.perl.org/Getopt/Std.html) – ssr1012

+2

Pourquoi chargez-vous Getopt :: Long, puis l'ignorez? –

Répondre

1

Votre code est incorrect. Veuillez parcourir la documentation en premier: http://perldoc.perl.org/Getopt/Long.html

Vous trouverez ci-dessous une tentative de deviner ce que vous essayiez d'obtenir.

use strict; 
use warnings; 
use Getopt::Long qw(GetOptions); 
my $city; 
print "raw data:@ARGV\n"; 
GetOptions ("city=s" => \$city) or die("Error in command line arguments\n"); 
my $site = $city; 
if($site){ 
    print "success: City is $city\n"; 
} 
print "Final data:@ARGV \n"; 

sortie:

[email protected]:~/Desktop$ perl test.pl -city=bangalore 
raw data:-city=bangalore 
success: City is bangalore 
Final data: 

sortie lorsqu'il est passé param incorrect:

[email protected]:~/Desktop$ perl test.pl -blah=blah 
raw data:-blah=blah 
Unknown option: blah 
Error in command line arguments 
+0

si je veux passer seulement les quatre villes comme (a, b, c, d) .Comment je peux passer dans array.if le nom de la ville est r il devrait imprimer sans succès. –

+0

S'il vous plaît passer par le lien, d'abord comprendre comment accepter les paramètres. Après cela, il suffit d'ajouter des conditions en fonction de vos besoins. –

+0

@test data, '--city a, b, c, d' est toujours un seul paramètre. Vous demandez en fait comment diviser une valeur. Vous pouvez utiliser: 'my @cities = $ city? split (/, /, $ ville):(); ' – ikegami

0

Thanks to: alvinalexander

#!/usr/bin/perl -w 

# a perl getopts example 
# alvin alexander, http://www.devdaily.com 

use strict; 
use Getopt::Std; 

# declare the perl command line flags/options we want to allow 
my %options=(); 
getopts("hj:ln:s:", \%options); 

# test for the existence of the options on the command line. 
# in a normal program you'd do more than just print these. 
print "-h $options{h}\n" if defined $options{h}; 
print "-j $options{j}\n" if defined $options{j}; 
print "-l $options{l}\n" if defined $options{l}; 
print "-n $options{n}\n" if defined $options{n}; 
print "-s $options{s}\n" if defined $options{s}; 

# other things found on the command line 
print "Other things found on the command line:\n" if $ARGV[0]; 
foreach (@ARGV) 
{ 
    print "$_\n"; 
}