您的位置:首页 > 编程语言 > Go语言

perl 中substr应用详解

2009-04-08 15:56 155 查看
 
#!/usr/bin/perl

#-----------------------------

#substr用来存取子串,可以修改子串,主要用法如下:

#$value = substr($string, $offset, $count);

#$value = substr($string, $offset);

#substr($string, $offset, $count) = $newstring;

#substr($string, $offset)         = $newtail;

#-----------------------------

# 首先得到一个5个字符的字符串,然后跳过三个字符,分别得到2个8字符的字符串,最后剩下的给$trailing

#unpack/pack的用法以后会讲到,或者参见google 一下 ‘perl函数 unpack’

($leading, $s1, $s2, $trailing) =

    unpack("A5 x3 A8 A8 A*", $data);

# 将字符串分成每5个字符一个串,存入数组@fives

@fivers = unpack("A5" x (length($string)/5), $string);

# 将字符串打散成单个字符,存入数组@chars

@chars  = unpack("A1" x length($string), $string);
#-----------------------------

$string = "This is what you have";
#         +012345678901234567890  Indexing forwards  (left to right)

#          109876543210987654321- Indexing backwards (right to left)

#           note that 0 means 10 or 20, etc. above

#下面是一些例子:

$first  = substr($string, 0, 1);  # "T"

$start  = substr($string, 5, 2);  # "is"

$rest   = substr($string, 13);    # "you have"

$last   = substr($string, -1);    # "e"

$end    = substr($string, -4);    # "have"

$piece  = substr($string, -8, 3); # "you"

#-----------------------------

$string = "This is what you have";
print $string;
#This is what you have

substr($string, 5, 2) = "wasn't"; # 改变 "is" 为 "wasn't"

#This wasn't what you have

substr($string, -12)  = "ondrous";# 替换最后12个字符

#This wasn't wondrous

substr($string, 0, 1) = "";       # 删除首字符

#his wasn't wondrous

substr($string, -10)  = "";       # 删除最后10个字符

#his wasn'

#-----------------------------

# 你可以用 =~ 来测试子串,=~为正则表达式匹配运算符,后面会讲到,还可以google Perl 正则表达式

#主要是匹配则为True;否则为False。 pattern可以自己根据需要构造。

if (substr($string, -10) =~ /pattern/) {

    print "Pattern matches in last 10 characters/n";
}

# 将 "is" 换为 "at", 限制在最后五个字符;=~ s/// 为替换表达式。

substr($string, 0, 5) =~ s/is/at/g;
#-----------------------------

# 将字符串$a的第一个和最后一个字符交换

$a = "make a hat";
(substr($a,0,1), substr($a,-1)) = (substr($a,-1), substr($a,0,1));
print $a;
# take a ham

#-----------------------------

# 抽取某些子串

$a = "To be or not to be";
$b = unpack("x6 A6", $a);  # 跳过6个字符,抽取6个字符

print $b;
# or not

($b, $c) = unpack("x6 A2 X5 A2", $a); # 跳过6个字符, 抽出2个字符的子串;后退5个字符,抽出2个字符的子串

print "$b/n$c/n";
# or

#

# be

#-----------------------------

#下面是一个综合的例子,主要是一个函数,实现了

#一种模板格式的输出。

sub cut2fmt {

    my(@positions) = @_;

    my $template   = '';

    my $lastpos    = 1;

    foreach $place (@positions) {

        $template .= "A" . ($place - $lastpos) . " ";

        $lastpos   = $place;

    }

    $template .= "A*";

    return $template;
}

$fmt = cut2fmt(8, 14, 20, 26, 30);
print "$fmt/n";
# A7 A6 A6 A6 A4 A*

#-----------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息