如何修复Perl中的多行失控字符串错误?

时间:2009-03-02 08:50:47

标签: perl

我的Perl脚本中有一些错误,我查看了源代码,但找不到问题。

#Tool: decoding shell codes/making shell codes

use strict;
use Getopt::Std;

my %opts=();
getopts("f:xa", \%opts);

my($infile, $hex);
my($gen_hex, $gen_ascii);

sub usage() {
print "$0 -f <file> [-x | -a] \n\t";
print '-p <path to input file>'."\n\t";
print '-x convert "\nxXX" hex to readable ascii'."\n\t";
print '-a convert ascii to "\xXX" hex'."\n\t";
print "\n";
exit;
}

$infile = $opts{f};

$gen_hex = $opts{a};
$gen_ascii = $opts{x};use


if((!opts{f} || (!$gen_hex && !$gen_ascii)) {
usage();
exit;
}

if($infile) {
open(INFILE,$infile) || die "Error Opening '$infile': $!\n"; 
while(<INFILE>) {
#Strips newlines
s/\n/g;
#Strips tabs
s/\t//g;
#Strips quotes
s/"//g;
$hex .= $_;
}
}

if($gen_ascii) {

# \xXX hex style to ASCII
$hex =~ s/\\x([a-fA-F0-9]{2,2})/chr(hex($1)/eg;
}
elsif ($gen_hex) {
$hex =~ s/([\W|\w)/"\\x" . uc(sprintf("%2.2x",ord($1)))/eg;
} 

print "\n$hex\n";
if($infile) {
close(INFILE);
}

给我错误

Backslash found where operator expected at 2.txt line 36, near "s/\"
(Might be runaway multi-line // string starting on line 34) 
syntax error at 2.txt line 25, near ") {"
syntax error at 2.txt line 28, near "}"
syntax error at 2.txt line 36, near "s/\"
syntax error at 2.txt line 41. nar "}"
Execution of 2.txt aborted due to compilation errors

你看到了问题吗?

4 个答案:

答案 0 :(得分:15)

#Strips newlines
s/\n/g;

错了。你忘记了额外的/

#Strips newlines
s/\n//g;

此外,这里的括号太少了:

if((!opts{f} || (!$gen_hex && !$gen_ascii)) {

而不是添加一些,你似乎有一个额外的。把它拿出来吧。

作为旁注,尽可能尝试use warnings;。这是一件好事。

编辑:当我在这里时,你可能要小心你的open()

open(INPUT,$input);

可以被滥用。如果$input">file.txt",该怎么办?然后open()会尝试打开文件进行编写 - 而不是你想要的。试试这个:

open(INPUT, "<", $input);

答案 1 :(得分:5)

有很多错误:use跟踪/s运算符中缺少ifuse strict; use Getopt::Std; my %opts = (); getopts( "f:xa", \%opts ); my ( $gen_hex, $gen_ascii ); sub usage() { print <<EOU $0 -f <file> [-x | -a] -p <path to input file> -x convert "\\xXX" hex to readable ascii -a convert ascii to "\\xXX" hex EOU } @ARGV = ( $opts{f} ) if exists $opts{f}; $gen_hex = $opts{a}; $gen_ascii = $opts{x}; if ( not( $gen_hex xor $gen_ascii ) ) { usage(); exit; } my $transform = $gen_ascii ? sub { s/\\x([a-fA-F0-9]{2,2})/pack'H2', $1/eg; } : sub { s/([^[:print:]])/'\\x'.uc unpack'H2', $1/eg; }; while (<>) { s/\n #Strips newlines | \t #Strips tabs | " #Strips quotes //xg; &$transform; print; } 表达式中的不平衡括号。有点整理:

{{1}}

答案 2 :(得分:1)

line25: if((!opts{f} || (!$gen_hex && !$gen_ascii)) {
line26: usage();

这是$ opts {f}

答案 3 :(得分:-2)

实际上,我认为错误就在这里:

s/"//g;

双引号应该被转义,以便该行变为:

s/\"//g;

您可以注意到,这是语法突出显示在SO上出错的行。