Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a macro in Perl

Tags:

macros

perl

open $FP, '>', $outfile or die $outfile." Cannot open file for writing\n";
  • I have this statement a lot of times in my code.

  • I want to keep the format same for all of those statements, so that when something is changed, it is only changed at one place.

  • In Perl, how should I go about resolving this situation?

  • Should I use macros or functions?

I have seen this SO thread How can I use macros in Perl?, but it doesn't say much about how to write a general macro like

#define fw(FP, outfile) open $FP, '>', \
        $outfile or die $outfile." Cannot open file for writing\n";
like image 229
Lazer Avatar asked Sep 07 '10 17:09

Lazer


2 Answers

First, you should write that as:

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

including the reason why open failed.

If you want to encapsulate that, you can write:

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);

Starting with Perl 5.10.1, autodie is in the core and I will second Chas. Owens' recommendation to use it.

like image 177
Sinan Ünür Avatar answered Oct 02 '22 13:10

Sinan Ünür


Perl 5 really doesn't have macros (there are source filters, but they are dangerous and ugly, so ugly even I won't link you to the documentation). A function may be the right choice, but you will find that it makes it harder for new people to read your code. A better option may be to use the autodie pragma (it is core as of Perl 5.10.1) and just cut out the or die part.

Another option, if you use Vim, is to use snipMate. You just type fw<tab>FP<tab>outfile<tab> and it produces

open my $FP, '>', $outfile
    or die "Couldn't open $outfile for writing: $!\n";

The snipMate text is

snippet fw
    open my $${1:filehandle}, ">", $${2:filename variable}
        or die "Couldn't open $$2 for writing: $!\n";

    ${3}

I believe other editors have similar capabilities, but I am a Vim user.

like image 23
Chas. Owens Avatar answered Oct 02 '22 11:10

Chas. Owens