简体   繁体   English

Perl正则表达式使用花括号提取匹配项

[英]Perl regex extracting a match using braces

I tested the following code 我测试了以下代码

#! /usr/bin/perl 

use strict;
use English;

#this code extracts the current scripts filename 
#by removing the path from the filepath

my $Script_Name = $PROGRAM_NAME;

${Script_Name} =~ s/^.*\\//; #windows path

#${Script_Name} =~ s/^.*\///; #Unix based path

print $Script_Name;

and i don't understand why these braces extract the match without using a /r modifier. 而且我不明白为什么这些花括号在不使用/ r修饰符的情况下提取匹配项。 can anyone explain why and how this works or point me to some documentation? 谁能解释为什么以及如何运作,或者向我介绍一些文档?

You're getting a little confused! 你有点困惑!

The braces make no difference. 括号没有区别。 ${Script_Name} is identical to $Script_Name . ${Script_Name}$Script_Name相同。

You code first copies the entire path to the script file from $PROGRAM_NAME to $Script_Name . 您的代码首先将脚本文件的整个路径从$PROGRAM_NAME $Script_Name$Script_Name

Then the substitution removes everything up to and including the last backslash, leaving just the file name. 然后替换操作将删除直到最后一个反斜杠(包括最后一个反斜杠)的所有内容,仅保留文件名。

The /r modifier would be used if you wanted to modify one string and put the result of the modification into another, so you could write your code in one step as 如果您想修改一个字符串并将修改的结果放入另一个字符串,则将使用/r修饰符,因此您可以一步编写代码,如下所示:

$Script_Name = $PROGRAM_NAME=~ s/^.*\\//r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM