Perl冒号分割显示一个字符

时间:2015-11-04 23:52:31

标签: perl

Perl冒号分割在变量中使用时显示一个字符。

代码

#!/usr/bin/perl

my $serialnumber= "0123456789";
my $macaddr = "a1:b2:c3:d4:e5:f6";
my $macaddress  = split /:/, $macaddr;

print $macaddress;
print "\n";

结果仅为" 6"或文本的最后一个字符。

见图片......

enter image description here

3 个答案:

答案 0 :(得分:4)

Sean explained为什么要获得6。但是,不是使用拆分,而只是substitute来摆脱冒号:

my $macaddr = "a1:b2:c3:d4:e5:f6";
$macaddr =~ s/://g;

print $macaddr;
# a1b2c3d4e5f6

答案 1 :(得分:3)

perldoc -f split的第一段说:

Splits the string EXPR into a list of strings and returns the
list in list context, or the size of the list in scalar context.

split的结果分配给标量变量$macaddress,您需要提供标量上下文,这样您就可以重新获得列表的大小。巧合的是,这恰好与输入字符串的最后一个字符相同。

答案 2 :(得分:0)

您可以在列表上下文中使用拆分:

my @macaddress  = split /:/, $macaddr;
print join "", @macaddress;