【发布时间】:2018-01-10 17:56:30
【问题描述】:
我需要将 Perl 程序作为更大的 R 程序的一部分来执行。
R 代码生成一系列具有不同扩展名的输出文件,例如.out 或.lis。
我有一个将这些文件转换为 CSV 的 Perl 程序。
我见过在 R 上执行 Perl 参数,但没有这种复杂性。
@outfiles = glob( "*.lis" );
foreach $outfile ( @outfiles ) {
print $outfile, "\n";
$outfile =~ /(\S+)lis$/;
$csvfile = $1 . "lis.csv";
print $csvfile, "\n";
open( OUTFILE, "$outfile" ) || die "ERROR: Unable to open $outfile\n";
open( CSVFILE, ">$csvfile" ) || die "ERROR: Unable to open $csvfile\n";
$lineCnt = 0;
while ( $outline = <OUTFILE> ) {
chomp( $outline );
$lineCnt++;
$outline =~ s/^\s+//; # Remove whitespace at the beginning of the line
if ( $lineCnt == 1 ) {
$outline =~ s/,/\./g; # Replace all the commas with periods in the hdr line
}
$outline =~ s/\s+/,/g; # Replace remaining whitespace delimiters with a comma
print CSVFILE "$outline\n";
}
close( OUTFILE );
close( CSVFILE );
}
有什么方法可以将 Perl 代码集成到我的 R 代码中?我可以开发一个 R 程序来做同样的事情。但我不知道从哪里开始将.lis 或.out 文件转换为.csv。
【问题讨论】:
-
添加 shebang 行 (
#!/usr/bin/perl) 并使文件可执行。然后,它就变成了从 R 启动可执行文件的问题。 -
那是生成 CSV 的可怕方式。使用文本::CSV_XS。 (如果输入真的是一个制表符分隔的文件,你还应该使用 Text::CSV_XS 来解析输入!)
-
我的 cmets 与您的问题无关,所以不,我无法详细说明。如果您希望审查您的代码,可以在 StackExchange 站点上执行此操作。 codereview.stackexchange.com
-
“没有这么复杂的东西。” 三十行!!