2

好吧,我的代码很简单。它应该打印 content + \n 但结果以某种方式反转。

这里的代码:

#!/usr/bin/perl -w 

use strict;

my $founds; 

while (<>){ 
    $$founds{$2} = $& while  m/([A-Z]{3})([a-z])([A-Z] {3})/g;                               
}

print sort keys %$founds, "\n";

结果是:

(here is a newline)  
abcdefghijklmnopqrstuvwxyz

希望您的配置也会发生这种情况(如果您想下载我在代码中使用的文件,请转到此处

无论如何,您对此有所了解吗?

PS:正则表达式不允许换行符,所以问题不太可能属于它。

4

2 回答 2

7

首先获得换行符的原因是由于缺少括号而将其包含在排序中。改为这样做:

print sort(keys %{$founds}), "\n";

换行符首先出现是巧合(或者更确切地说,由于是非空白字符中的空白字符)。

为了澄清:

my %found = ( foo => 1, bar => 1 );   # keys returns "foo", "bar"
print sort keys %found, "\n";         # sort gets "foo", "bar", "\n"
         # ^^^^^^^^^^^^^^^^^----------- arguments to sort()
于 2013-07-21T23:39:18.637 回答
-2

perl 中每个输入行的末尾都有一个换行符。你需要chomp在你的while循环中做第一件事

use strict;

my $founds; 

while (<>){ 
   chomp;
   $founds->{$2} = $& while  m/([A-Z]{3})([a-z])([A-Z] {3})/g;                               
}

print sort keys %{$founds}, "\n";

您还应该使用 -> 符号来访问引用,我会将 % 取消引用括在大括号中以帮助易读性

于 2013-07-21T23:37:54.943 回答