"echo" html 内容到 perl 文件

eex*_*ess 0 perl

我经常在 perl 中使用“echo $xxx >file”,通常用于调试。它丑陋但简单,它适合“有不止一种方法可以做到”。

但现在我有一个问题@_@_包含一个网页。

`echo "@_" >/tmp/curl`;
`echo """@_""" >/tmp/curl`;

sh: -c: line 5: syntax error near unexpected token `<'
sh: -c: line 5: ` <meta description="

`echo "'"@_"'" >/tmp/curl`;
`echo '"'@_'"' >/tmp/curl`;

sh: -c: line 0: syntax error near unexpected token `newline'
sh: -c: line 0: `echo "'"<html>'
Run Code Online (Sandbox Code Playgroud)

我想知道这是否可以做到。

ps:我测试了 bash,它在终端中工作。

r='<meta description="Ch<br><br>This'; echo $r >/tmp/curl
Run Code Online (Sandbox Code Playgroud)

但是 perl 不能。

#!/usr/bin/perl
$r='<meta description="Ch<br><br>This';
`echo "$r" >/tmp/curl`; exit;
Run Code Online (Sandbox Code Playgroud)

我觉得这里有一些技巧可以做到。

ilk*_*chu 5

哦,亲爱的,没有。您对反引号所做的事情是生成一个 shell,只是为了将某些内容打印到文件中。如您所见,特殊字符会导致问题,并允许注入命令。理论上,您可以逃避 shell 认为特殊的所有内容,但这样做很烦人。

只需使用正确的文件处理函数并创建一个包含所有步骤的函数:

sub dumptofile($@) {
    my $file = shift;
    if (open F, ">", $file) {
        print F @_;
        close F; 
    } else {
        warn "Can't open $file: $!"
    }
}

dumptofile("/tmp/curl", "some output\n");
Run Code Online (Sandbox Code Playgroud)

现在,如果你不想输入所有这些,你可以把它压缩成更难看的东西,忽略错误检查和所有(就像我的第一个版本一样)。或者将完整版本保存在一个模块中,并将其放在 Perl 的包含路径中的某个位置(请参阅 参考资料perl -I)。

# Dumptofile.pm
package Dumptofile;
use strict;
use warnings;
use Exporter qw/import/;
our @EXPORT = qw/dumptofile/;

sub dumptofile($@) {
    my $file = shift;
    if (open my $fh, ">", $file) {
        print $fh @_;
        close $fh; 
    } else {
        warn "Can't open $file: $!"
    }
}
1;
Run Code Online (Sandbox Code Playgroud)

用:

perl -MDumptofile -e 'dumptofile("out.txt", "blahblah");
Run Code Online (Sandbox Code Playgroud)