首页 > 解决方案 > 将 PWD 最后一个值分配给 perl 模块中的变量

问题描述

我想分配给$runperl 模块中的变量并检查 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.

标签: perlvariable-assignmentperl-module

解决方案


您不能在 Perl 中使用 bash 语法。

$run = ${PWD##*/};

右手边是一种 bash 的表达方式“删除最后一个斜线之前的所有内容”,在 Perl 中写为

$run = $ENV{PWD} =~ s{.*/}{}r;

或者

$run = substr $ENV{PWD}, 1 + rindex $ENV{PWD}, '/';

推荐阅读