perl - 将 PWD 最后一个值分配给 perl 模块中的变量
问题描述
我想分配给$run
perl 模块中的变量并检查 if 条件。基本上,$run
变量分配有当前工作目录的最后一个值,如果 perl 脚本正在检查分配给变量的值,则在 if 条件下$run
perl 模块代码脚本片段的一部分,其中已经看到了确切的问题。
ex.pm
-----
my $run = ${PWD##*/};
if ( $2 ne $run)
{
die "$0 should be run in a $run directory.";
}
使用此代码,我遇到了编译问题。如果直接具有最后一个路径值的 if 条件硬编码它的工作良好,则同样的事情if ( $2 ne '4')
。
编译问题消息
syntax error at bin/ex.pm line 44, near ")
{"
syntax error at bin/ex.pm line 49, near "$sitepath "
BEGIN not safe after errors--compilation aborted at bin/TestConstants.pm line 72.
Compilation failed in require at bin/ex1.pm line 13.
BEGIN failed--compilation aborted at bin/ex1.pm line 13.
Compilation failed in require at ./bin/test.pl line 26.
BEGIN failed--compilation aborted at ./bin/test.pl line 26 (#1)
(F) Probably means you had a syntax error. Common reasons include:
A keyword is misspelled.
A semicolon is missing.
A comma is missing.
An opening or closing parenthesis is missing.
An opening or closing brace is missing.
A closing quote is missing.
解决方案
您不能在 Perl 中使用 bash 语法。
$run = ${PWD##*/};
右手边是一种 bash 的表达方式“删除最后一个斜线之前的所有内容”,在 Perl 中写为
$run = $ENV{PWD} =~ s{.*/}{}r;
或者
$run = substr $ENV{PWD}, 1 + rindex $ENV{PWD}, '/';
推荐阅读
- java - Java中的Lambda:查找重复的id并抛出异常
- c# - 未保存 Powerpoint 图表数据
- python - 读取文件,如何只选择以整数开头的行?
- google-sheets - Google Drive 错误:抱歉,目前无法打开文件。请检查地址并再试一次。(谷歌表格)
- typescript - Chart.js 不显示
- c# - c#在图表区域外放置注释
- api - Cowin API 可以实时访问吗?
- html - 如何在html和css中获得相同高度的所有列
- jersey - 应用程序/Json 在 MultipartEntityBuilder 中转换为文本/纯文本
- python - 赋值前引用的局部变量“pts”