【问题标题】:Assigning PWD last value to variable in perl module将 PWD 最后一个值分配给 perl 模块中的变量
【发布时间】:2021-09-19 16:00:00
【问题描述】:

我想分配给 perl 模块中的变量 $run 并检查 if 条件。 基本上,$run 变量分配有当前工作目录的最后一个值,如果 perl 脚本正在检查分配有变量 $run 的值,则在 if 条件下。

perl 模块代码脚本 sn-p 的一部分,其中已经看到了确切的问题。

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 variable-assignment perl-module


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • $run = $ENV{PWD} =~ s{.*/}{}r; 这里变量 $run 被分配了$ENV{PWD}$ENV{PWD} 被分配了=~ s{.*/}{}r;。这条线是怎么回事?加上这一行会有编译问题。
    • 不,在$ENV{PWD} 中直到最后一个/ 的所有内容都替换为空字符串,并将结果分配给$runr 修饰符需要 Perl 5.14+ 才能工作(10 岁)。
    猜你喜欢
    • 2012-04-09
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2012-06-06
    • 1970-01-01
    相关资源
    最近更新 更多