1

有人能指出我的错误吗?

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

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

4

2 回答 2

5

的反面"1234567\n""\n7654321"。如果要在反转之前去掉换行符,可以使用内置chomp函数

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
  }
}
于 2013-05-14T01:04:06.617 回答
1

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

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

while (<>) {
   chomp;
   if( 5 < length ){
      say "".reverse;
   } else {
      say;
   }
}
于 2013-05-14T01:03:39.603 回答