Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl right way to write macros

Tags:

perl

In order to simplify my program, I would like to write some macros that I can use in different subroutines.

Here's what I wrote:

my @m = ();
sub winit   { @m = (); }
sub w       { push @m, shift; }
sub wline   { push @m, ''; }
sub wheader { push @m, commentHeader(shift); }
sub walign  { push @m, alignMakeRule(shift); }
sub wflush  { join($/, @m); }

sub process {
    winit;

    w "some text";
    wline;

    wheader 'Architecture';   
    w getArchitecture();
    wline;

    say wflush;
}

Is there a better way or a smarter way to do what I want to do?

like image 828
nowox Avatar asked Dec 28 '25 10:12

nowox


2 Answers

You can use closure, or hash of closures if you find such approach useful,

use strict;
use warnings;
use feature 'say';

sub winit {
  my @m;
  return (
    w       => sub  { push @m, shift; },
    wline   => sub  { push @m, ''; },
    wheader => sub  { push @m, "commentHeader ". shift; },
    walign  => sub  { push @m, "alignMakeRule ". shift; },
    wflush  => sub  { join($/, @m); },
  );
}

sub process {
    my %w = winit();

    $w{w}->("some text");
    $w{wline}->();

    $w{wheader}->('Architecture');   
    $w{w}->("getArchitecture()");
    $w{wline}->();

    say $w{wflush}->();
}

process();
like image 121
mpapec Avatar answered Dec 31 '25 01:12

mpapec


If I've understood what you're trying to do, what I'd be thinking is to start looking at object oriented perl.

Objects are way of building complex data structures, and 'building in' code to 'do things' to the data structure.

So you'd create an object (perl module):

#!/usr/bin/perl
use strict;
use warnings;

package MyMacro;

sub new {
    my ($class) = @_;
    my $self = {};
    $self->{m} = ();
    bless( $self, $class );
}

sub flush {
    my ($self) = @_;
    return join( $/, @{ $self->{m} } );
}

sub addline {
    my ($self) = @_;
    push( @{$self -> {m}}, '' );
}

sub addtext {
    my ( $self, $text ) = @_;
    push ( @{$self -> {m}}, $text );
}

#etc. for your other functions

1;

And then 'drive' it with:

use strict;
use warnings;
use MyMacro;

my $w = MyMacro->new();

$w->addtext("some text");
$w->addline();
$w->addtext("some text");

print $w ->flush;

This is pretty basic OOP, but you can do more advanced with Moose.

like image 27
Sobrique Avatar answered Dec 31 '25 01:12

Sobrique



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!