perl 自定义包/模块的使用(正则表达式匹配email地址和ip)

这篇博客介绍了Perl中正则表达式的基础用法,如匹配邮箱和IP地址,并探讨了自定义包和模块的定义及使用。作者强调Perl的开放性和正则表达式的复杂性,同时提醒读者注意模块间的依赖安装。

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

1. 正则表达式

email: =~ /^([0-9a-zA-Z]{3,}|[0-9a-zA-Z]+(-|_)?[0-9a-zA-Z_-]+\.?[0-9a-zA-Z]+)\@[0-9a-zA-Z]+\.[0-9a-zA-Z]+(\.\w+)?/;

ip =~/([0-9]{1,3}\.?){4}/;

 

. Match any character except a wrap character.

\w Match "word" character and [_0-9a-zA-Z]

\W Match non-word character  [^_0-9a-zA-Z]

\s  Match whitespace character [ \r\t\n\f]

\S Match non-whitespace character [^ \r\t\n\f]

\d  Match digit character [0-9]

\D Match non-digit character [^0-9]

\t  Match tab

\n Match newline

^ Match the head

$ Match the end

*  Match 0 or more times

+  Match 1 or more times

?  Match 0 or 1 times

{n} Match exactly n times

{n,} Match at least n times

 {n,m} Match at least n but not more than m times

a|b  match a or match b

2.自定义包/模块

包和模块的区别:

1.一个包的定义可以跨多个模块,一个模块中也可以有多个包定义;

2.定义模块时模块名必须和文件名一致,包无此要求;

注意:包和模块文件末尾需要加1;(return 1)

 

比如: 定义包名为getip.pm 在包文件里写入package getip;

View Code 
 #!/usr/bin/perl -w
 package packagetest;
 use strict;
 sub get_local_ip
 {
   chomp(my $ip=`ifconfig eth0|grep -oE '([0-9]{1,3}\\.?){4}'|head -n 1`);
   return $ip;
 }
 sub check_email
 {
   my $temp=$_[0];
   if($temp=~/^([0-9a-zA-Z]{3,}|[0-9a-zA-Z]+(-|_)?[0-9a-zA-Z_-]+\.?[0-9a-zA-Z]+)\@[0-9a-zA-Z]+\.[0-9a-zA-Z]+(\.\w+)?/)
   {
    return $temp;
   }
   else
   {
     return $temp="illegal email address!"
   }
 }
 1;


 

3.如何使用

使用自定义包,在perl文件加入

package packagetest;(和包放在同一目录下)

使用函数:

包名::函数名

View Code 
 #!/usr/bin/perl -w
 require "package.pm";
 package packagetest;
 $localip=&packagetest::get_local_ip;
 print $localip;
 print "\n";
 $mail=&packagetest::check_email('someone_example@cn.com');
 print "$mail\n";
 [root@localhost perl]# more getip.pl 
 #!/usr/bin/perl -w
 require "package.pm";
 package packagetest;
 $localip=&packagetest::get_local_ip;
 print $localip;
 print "\n";
 $mail=&packagetest::check_email('someone_example@cn.com');
 print "$mail\n";


 

总结:

1. perl很开放,正则表达式也很深奥,很多情况perl不报错但是结果是错的。

2.perl模块很多,有些模块依赖别的模块,需要一一安装。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值