1
我有這個字符串我怎麼會修剪和分裂成Perl中的哈希
$st="station_1:50, station_2:40, station_3:60";
我將如何分割成一個Perl的哈希表呢?
我嘗試
%hash = map{split /\:/, $_}(split /, /, $st);
它正確的 - 但如果存在之間站n維空間,是什麼? 我將如何讓它脫去所有的領先空間?
我有這個字符串我怎麼會修剪和分裂成Perl中的哈希
$st="station_1:50, station_2:40, station_3:60";
我將如何分割成一個Perl的哈希表呢?
我嘗試
%hash = map{split /\:/, $_}(split /, /, $st);
它正確的 - 但如果存在之間站n維空間,是什麼? 我將如何讓它脫去所有的領先空間?
如果有可能或不可能有空間,分割/, ?/
而不是/, /
。如果可能有多個空格,請使用/, */
。
與您的代碼(加入\s*
到第二split
)的溶液:
perl -we '
my $_ = "station_1:50, station_2:40, station_3:60";
my %hash = map {split /:/} split /,\s*/;
use Data::Dumper;
print Dumper \%hash
'
OUTPUT:
$VAR1 = {
'station_1' => '50',
'station_3' => '60',
'station_2' => '40'
};
另一種工作方式使用正則表達式:
CODE
$ echo "station_1:50, station_2:40, station_3:6" |
perl -MData::Dumper -lne '
my %h;
$h{$1} = $2 while /\b(station_\d+):(\d+)/ig;
print Dumper \%h
'
樣本輸出
$VAR1 = {
'station_3' => '6',
'station_1' => '50',
'station_2' => '40'
};
[分割具有多個空格用Perl的字符串η]可能重複(http://stackoverflow.com/questions/3366533/splitting-a-string-with-multiple-white-空間與 - perl的) – Flimzy 2014-11-06 03:25:30