perl - 用 Perl 编写宏

标签 perl macros

open $FP, '>', $outfile or die $outfile." Cannot open file for writing\n";
  • 我的代码中有很多次这样的声明。
  • 我想保持所有这些语句的格式相同,这样当某些内容发生变化时,它只会在一个地方发生变化。
  • 在 Perl 中,我应该如何解决这种情况?
  • 我应该使用宏还是函数?

  • 我见过这个 SO 线程 How can I use macros in Perl? ,但它并没有说明如何编写一个通用的宏,比如
    #define fw(FP, outfile) open $FP, '>', \
            $outfile or die $outfile." Cannot open file for writing\n";
    

    最佳答案

    首先,你应该把它写成:

    open my $FP, '>', $outfile or die "Could not open '$outfile' for writing:$!";
    

    包括原因open失败的。

    如果你想封装它,你可以写:
    use Carp;
    
    sub openex {
        my ($mode, $filename) = @_; 
        open my $h, $mode, $filename
            or croak "Could not open '$filename': $!";
        return $h;
    }
    
    # later
    
    my $FP = openex('>', $outfile);
    

    从 Perl 5.10.1 开始,autodie是核心,我将第二个 Chas。 Owens 建议使用它。

    关于perl - 用 Perl 编写宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3661161/

    相关文章:

    用于获取日期范围的 perl 子例程

    regex - perl中匹配IP

    Emacs move-end-of-line、[END] 或 C-e 不移动到行尾?

    c++ - #ifdef _DEBUG 在主函数中

    java - Perl校验和计算迁移到Java

    perl - 为什么 Perl 的 Inline::C 在 4.4e-5 之后对 4.0e-5 进行排序?

    perl - 是否可以使用 while(my($key, $value) ... ) {} 方法按排序顺序遍历哈希?

    c++ - #定义空格

    c - 用 C 中的宏替换具有常量字符串参数的函数

    macros - 如何在运行时打印 Nim 的 AST?