如何删除perl反向额外线

时间:2013-05-14 01:00:23

标签: perl

有人可以指出我的错误吗?

while(<STDIN>){
  my $reverse = reverse $_; #(explicit - to force casting)
  if( 5 <length ){
        print "Reverse is $reverse\n";
  }
  else{
    print; #this will print $_ scalar context
  }
}

执行程序

1234567
Reverse is
7654321

但如果我改变了 print "Reverse is $reverse\n";print "$reverse\n"

1234567

7654321

有人可以解释发生了什么吗?我怎么能删除换行符?

2 个答案:

答案 0 :(得分:5)

"1234567\n"的反面是"\n7654321"。如果您想在撤消之前删除换行符,可以使用the built-in chomp function

while(<STDIN>){
  chomp;
  my $reverse = reverse $_; #(explicit - to force casting)
  if( 5 <length ){
        print "Reverse is $reverse\n";
  }
  else{
    print "$_\n"; #this will print $_ scalar context
  }
}

答案 1 :(得分:1)

添加chomp;作为循环的第一行,并使用say;print "$_\n";代替print;来补偿已删除的换行符。

use strict;
use warnings;
use feature qw( say );

while (<>) {
   chomp;
   if( 5 < length ){
      say "".reverse;
   } else {
      say;
   }
}