以下是我的perl脚本的全部内容:
#!/usr/bin/perl
use v5.10;
use strict;
#use P4;
print "enter location of master_testplan.conf:";
my $master_testplan_conf = <>;
if (chomp($master_testplan_conf) eq "")
{
$master_testplan_conf = 'suites/MAP/master_testplan.conf';
}
print ":" . $master_testplan_conf . ":";
引用this answer,我认为这会奏效。但是由于某种原因,它没有在if语句中获得默认值。
我做错了什么?
答案 0 :(得分:5)
chomp
不起作用。它直接修改传递给它的变量并返回扼杀的字符数。这样做:
chomp $master_testplan_conf;
if ($master_testplan_conf eq "") {
# etc.
}
答案 1 :(得分:2)
chomp
修改其参数并且不返回它,因此您必须将条件重写为:
chomp($master_testplan_conf);
if ($master_testplan_conf eq "") {
答案 2 :(得分:2)
来自chomp的文档:
..It returns the total number of characters removed from all its arguments..
所以你需要首先选择,然后比较空字符串。例如:
chomp($master_testplan_conf = <>);
if ($master_testplan_conf eq "") {
// set default value
}
答案 3 :(得分:1)
一些事情:
Chomp更改字符串,并返回字符 chomped 的数量。在该输入行之后,chomp $master_testplan_conf
最有可能1
,因此您需要将1
与空字符串进行比较。
你可以这样做:
chomp ( $master_testplan_conf = <> );
如果你想在一行上做所有事情。
这将读取您的输入并一步完成chomp。此外,<>
运算符将从命令行获取文件,<>
将是命令行中第一个文件的第一行。如果您不想这样做,请使用<STDIN>
:
chomp ( $master_testplan_conf = <STDIN> );
您可能想要清理用户的输入。我至少会删除任何领先和结束的空白:
$master_testplan_conf =~ s/^\s*(.*?)\s*$/$1/; # Oh, I wish there was a "trim" command!
这样,如果用户不小心按了几次空格键,你就不会拿起空格。您也可能想要测试文件是否存在:
if ( not -f $master_testplan_conf ) {
die qq(File "$master_testplan_conf" not found);
}
我还建议使用:
if ( not defined $master_testplan_conf or $master_testplan_conf eq "" ) {
代表您的if
语句。这将测试$master_test_conf
是否实际定义而不仅仅是空字符串。现在,这并不重要,因为用户必须至少输入\n
。 $master_testplan_conf
漫步永远不会为空。
但是,如果您决定使用Getopt::Long,则可能很重要。
答案 4 :(得分:0)
正则表达式可以很方便地检查而不改变任何东西:
if ($master_testplan_conf =~ /^\s*$/)
{
$master_testplan_conf = 'suites/MAP/master_testplan.conf';
}
还要检查undef:
if (!defined $master_testplan_conf || $master_testplan_conf =~ /^\s*$/)
{
$master_testplan_conf = 'suites/MAP/master_testplan.conf';
}
答案 5 :(得分:0)
您对文件而不是字符串本身感兴趣,因此请使用Perl文件测试。在这种情况下,请使用文件测试存在(-e
):
if (-e $master_testplan_conf) {
这触及问题的核心,让您知道输入是否存在于文件系统中。