[转 - 改] Perl初级教程 (四)

本文介绍了Perl中的正则表达式基本用法及特殊字符含义,并展示了如何使用~操作符来进行字符串匹配。此外,还讲解了两个特殊变量$$和$_的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串匹配

  则表达式-regular expression

   规则表达式包含在斜线内,匹配通过=~操作符进行。如果字符串the出现在变量$sentence中,则下面的表达式为真:

    $sentence =~ /the/

  RE是大小写敏感的,所以如果

  $sentence = "The quick brown fox";

  那么上面的匹配结果为false。

   


$TestStr   =   " Contains a test ! "  ;
if  ( $TestStr   =   !   ~/ test / )
{
    
print ( " Contain !  " );
}
else
{
    
print ( " No contain ! " );
}
>   No  contain !

 

下面是一些特殊的RE字符和它们的意义:

.	# Any single character except a newline
^	# The beginning of the line or string
$	# The end of the line or string
*	# Zero or more of the last character
+	# One or more of the last character
?	# Zero or one of the last character

 

 【特殊变量[URL]

   1. $$

   perl -e "sleep(5);print qq(The PID of process perl.exe is : $$)";  # 命令行运行, $$是当前perl解析器的进程ID(即,PID).

> The PID of process perl.exe is : 1871

   2. $_.

  

@FruitList   =  ( " Apple  " , " Pear  " , " Orange  " , " Peach  " );

foreach ( @FruitList )
{
print   $_ . " \n " ;
}
> Apple
  Pear
  Orange
  Peach
 

在程序第五行中:foreach (@array) 实际上就是等于 foreach $_ (@array),在这里,$_是默认是输入/输出,因此,如果在程序中有类似的没有明确声明的变量位置的时候,就有可能能使用$_代替。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值