2013-08-23 102 views
-1

好吧,这让我疯狂!我的Perl语句有什么问题?

看了很多例子,并阅读了perl中的if语句,并且所有内容对我来说都是正确的,所以其他人可以发现错误吗?

#Start of script 
#!/usr/bin/perl -w 

########################## 
#### Define Variables #### 
########################## 
echo $PWD; 
mainDirectory=$ENV{HOME}"/test/"; 
file='report.txt'; 
backupDirectory=$ENV{HOME}"/test/backup"; 
number_to_try=0; 

################################## 
#### Check if the file exists #### 
################################## 
filename=$mainDirectory$file; 
echo $filename; 

if (-e $filename) { 
    print "File Exists!" 
} 

错误消息我得到的是:

./perl.pl: line 18: syntax error near unexpected token `{' 
./perl.pl: line 18: `if (-e $filename) {' 

人有什么想法?

+8

这个Perl怎么样? – Jean

+0

其开始的perl脚本...#!/ usr/bin/perl ..它怎么样? – Fuzzybear

+2

这主要写在'sh'中,除了结尾的条件和'%ENV'哈希。使用错误的shebang不会奇迹般地解决这个问题。 Perl没有'echo'。变量被赋值为'$ foo ='$ ENV {HOME}/test /“;'(注意LHS上的$ $ sigil) – amon

回答

6

上面的所有行“if”都是无效的Perl;我相信你想这样做:

#!/usr/bin/perl 
use strict; 
use warnings; 

########################## 
#### Define Variables #### 
########################## 

my $mainDirectory = "$ENV{HOME}/test"; 
my $file = 'report.txt'; 
my $backupDirectory = "$ENV{HOME}/test/backup"; 
my $number_to_try = 0; 

################################## 
#### Check if the file exists #### 
################################## 

my $filename = "$mainDirectory/$file"; 
print "$filename\n"; 

if (-e $filename) { 
     print "File Exists!\n"; 
} 
+3

'严格使用;使用警告;'被认为比'-w更好 - 使用严格;' –

+1

@KithithThompson我同意,“使用警告”这个文件只比在程序范围内使用“-w”更好,并且冒着烦人任何模块的风险使用。 (我通常在可以的时候戳掉“-w”。) – kjpires

+0

绝妙的答复感谢你,也从这一切中学到了一些新东西...... shebang必须在第一行......或者它只会解释它如同sh。感谢您的建设性意见:) – Fuzzybear

1

改写为最小变化:

#!/usr/bin/perl -w 

########################## 
#### Define Variables #### 
########################## 

#echo $PWD; 
$mainDirectory=$ENV{HOME}."/test/"; 
$file='report.txt'; 
$backupDirectory=$ENV{HOME}."/test/backup"; 
$number_to_try=0; 

################################## 
#### Check if the file exists #### 
################################## 
$filename=$mainDirectory.$file; 
#echo $filename; 

if (-e $filename) { 
    print "File Exists!" 
} 

强烈建议使用use strict;use warnings;虽然。

+0

“print”后面的分号文件存在!“'? – rutter

+1

@rutter在块中的尾部分号是可选的:'{foo()}'与'{foo();;;;;}' – amon

+0

'相同如果不使用'use strict',Perl会容忍它:) – Jean