如何将文件foo2.txt附加到foo1.txt?

时间:2010-01-21 11:43:37

标签: perl append

是否有任何方法可以从Perl中的 foo1.pl 执行 foo2.pl ,并将 foo2.txt 附加到 foo1.txt 然后创建 foo3.txt ?感谢。

foo1.pl

 print "Hello"; # output to foo1.txt;

foo2.pl

 print "World"; # output to foo2.txt;

如何根据 foo1.pl 创建 foo3.txt 文件。

foo3.txt

Hello
World

foo2.txt 附加到 foo1.txt

据我所知,我可以打开 foo1.txt foo2.txt ,然后在 foo3.pl 中包含这些行。

print FOO3_TXT (<FOO1_TXT>);
print FOO3_TXT (<FOO2_TXT>);

有什么好方法吗?


更新我的测试(ActivePerl 5.10.1)

我的foo.pl

#!C:\Perl\bin\perl.exe
use strict;
use warnings;

print "world\n";

我的 hw.pl (同一目录下的foo.pl和hw.pl)

#!C:\Perl\bin\perl.exe
use strict;
use warnings;

print 'hello '; 
print `./foo.pl`;

输出

** d:\学习\ perl的&GT; hw.pl

  

你好'。'不被视为内部或外部命令,   可操作程序或批处理文件。**

如果hw.pl已更新{}:

#!C:\Perl\bin\perl.exe
use strict;
use warnings;

print q{hello }, qx{./foo.pl};

现在输出。 (对于你好的放松而言略有不同)

d:\学习\ perl的&GT; hw.pl ''不被视为内部或外部命令, 可操作程序或批处理文件。 喂

[更新]。

固定。见答案,

5 个答案:

答案 0 :(得分:2)

将其作为脚本运行

perl foo1.pl > foo3.txt;
perl foo2.pl >> foo3.txt;

foo1.pl的内容

!#/bin/perl
print "Hello";

foo2.pl的内容

!#/bin/perl
print "World";

如果您正在运行linux以将foo2.txt附加到foo1.txt,则只需使用cat命令。

答案 1 :(得分:1)

如果你是关于execute foo2.pl from foo1.pl in Perl的字面意思,那么你就可以做到这一点:

print 'hello ';
print qx(perl foo2.pl);

qx是另一种运行反引号等系统命令的方法。因此,perl foo2.pl运行时输出将被发送回您的调用perl脚本。

所以这里使用反引号一样。它还使用直接调用脚本(这是更好的):

print 'hello ';
print `./foo2.pl`;

如果你期望脚本有很多输出,那么最好不要像上面两个例子那样将它全部加载到内存中。而是像这样使用open

print 'hello ';
open my $foo2, '-|', './foo2.pl';
print <$foo2>;
close $foo2;

你可以将它包装成一个打印语句,用于“hello world”示例:

print 'hello ', do {
   open my $foo2, '-|', './foo2.pl';
   <$foo2>;
};

/ I3az /

答案 2 :(得分:1)

使用shell脚本(例如,Windows上的.bat文件)来运行各种Perl脚本并组合它们的输出是解决问题的一种方法。但是,我通常发现Perl本身提供了比shell脚本更强大,更灵活的环境。要以这种方式使用Perl,首先要了解systemexec命令。

例如:

# In hello.pl
print "Hello\n";

# In world.pl
print "World\n";

# In hello_world.pl.
use strict;
use warnings;
system 'perl hello.pl >  hello_world.txt';
system 'perl world.pl >> hello_world.txt';

答案 3 :(得分:1)

您也可以使用以下代码

file1.pl

use strict;
use warnings;

open (FH,">file") or die "$! can't open";
print FH "WELCOME\n";

file2.pl

use strict;
use warnings;

open (FH,">>file") or die "$! can't open";
print FH "WELCOME2\n";

文件内容为

WELCOME 
WELCOME2 

答案 4 :(得分:0)

如果您知道要在其他脚本中执行的脚本也是Perl,则应使用do EXPRhttps://perldoc.perl.org/functions/do.html)。 这将在运行的perl进程的上下文中执行文件EXPR的内容,并使您免于启动新的cmd.exe和perl.exe实例。

hello.pl:
print "Hello";
do "world.pl";

wordl.pl:
print "World";
相关问题