在Perl中说功能

时间:2018-07-11 08:11:44

标签: perl

我有一个下面的Perl代码

$fs_headerrecord_cut_casettenumber_pad_len = 2;
$fs_headerrecord_batch_casettenumber_start_pos = 21;
$fs_headerrecord_batch_casettenumber_data_len = 2;
$fs_header_record = 1;
$pad_length = 0;
my $dir = ".";
opendir(DIR, $dir) or die "Cannot open directory: $dir!\n";
my @files = readdir(DIR);
closedir(DIR);

open my $out, ">>output.txt" or die "Cannot open cutfile!\n";
foreach my $file (@files) {

    #next unless (-M $file <= 1 && $file =~ /^fs.*\.DTA$/i) ;
    if (-M $file <= 1 && $file =~ /^fs.*\.DTA$/i) {
        #print log_date() ."$file\n";
        print "$file\n";
        open my $fs_in, "<$file" or die "Cannot open $file!\n";
        while (<$fs_in>) {
            $recordlength = substr($_,220,1);
            if ($recordlength == $fs_header_record) {
                say $out ' ' x $pad_length, 'H', substr($_,0,1), say $out ' ' x $fs_headerrecord_cut_casettenumber_pad_len, substr($_, $fs_headerrecord_batch_casettenumber_start_pos, $fs_headerrecord_batch_casettenumber_data_len);

我想在casettenumber之前写“ H”。我得到的输出如下

OUTPUT



14
H 1
  14
H 1
  14
H 1
  14
H 1
  14
H 1
  14

预期产量

H 14
H 14
H 14
H 14
H 14

当我打印“ H”时,它将在新行中打印。有人可以告诉我我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

您使用的是2条,所以您将打印2条换行符。

请参阅:打印与说:

https://perldoc.perl.org/functions/print.html

https://perldoc.perl.org/functions/say.html

另外,由于要打印第二个say的返回值作为第一个say的参数,因此还要打印额外的“ 1”。

尝试替换此:

say $out ' ' x $pad_length, 'H', substr($_,0,1), say $out ' ' x $fs_headerrecord_cut_casettenumber_pad_len, substr($_, $fs_headerrecord_batch_casettenumber_start_pos, $fs_headerrecord_batch_casettenumber_data_len);                

与此:

print $out ' ' x $pad_length, 'H', substr($_,0,1);
say $out ' ' x $fs_headerrecord_cut_casettenumber_pad_len, substr($_, $fs_headerrecord_batch_casettenumber_start_pos, $fs_headerrecord_batch_casettenumber_data_len);

或将所有数据发送到相同的say语句:

say $out 
    ' ' x $pad_length, 'H', 
    substr($_,0,1),
    $out ' ' x $fs_headerrecord_cut_casettenumber_pad_len, 
    substr($_, $fs_headerrecord_batch_casettenumber_start_pos, $fs_headerrecord_batch_casettenumber_data_len);