下面是幾種方法來做到這一點,但要小心 - 修改一個哈希鍵可以用不想要的結果結束,如:
use strict;
use warnings;
use Data::Dumper;
my $src = {
"a a" => 1,
" a a " => 2,
"' a a '" => 3,
};
print "src: ", Dumper($src);
my $trg;
@$trg{ map { s/^[\s']*(.*?)[\s']*$/$1/; $_ } keys %$src } = values %$src;
print "copy: ", Dumper($trg);
會產生:
src: $VAR1 = {
' a a ' => 2,
'\' a a \'' => 3,
'a a' => 1
};
copy: $VAR1 = {
'a a' => 1
};
任何正則表達式是可能的請使用YAPE :: Regex :: Explain模塊進行解釋。 (來自CPAN)。對於上述正則表達式:
use YAPE::Regex::Explain;
print YAPE::Regex::Explain->new(qr(^[\s']*(.*?)[\s']*$))->explain;
會產生:
正則表達式:
(?-imsx:^[\s']*(.*?)[\s']*$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with^and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
[\s']* any character of: whitespace (\n, \r, \t,
\f, and " "), ''' (0 or more times
(matching the most amount possible))
----------------------------------------------------------------------
( group and capture to \1:
----------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
----------------------------------------------------------------------
) end of \1
----------------------------------------------------------------------
[\s']* any character of: whitespace (\n, \r, \t,
\f, and " "), ''' (0 or more times
(matching the most amount possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
總之:s/^[\s']*(.*?)[\s']*$/$1/;
平均:
- 在字符串匹配的開始空格或撇號儘可能多次,
- 然後在字符串空格或撇號的末尾儘可能多的次數儘可能
- 匹配匹配任何內容,並保持只有「東西」的一部分
完美。這工作正常,我現在可以拉取哈希值。非常感謝您的寶貴時間。 – slayedbylucifer 2012-07-20 08:51:15