Pearl write macros correctly
To keep my program simpler, I would like to write some macros that can be used in different routines.
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?
+3
source to share
2 answers
You can use closure or closure hash if you find this 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();
+3
source to share
If I understood what you are trying to do, then I would think to start looking at object oriented perl.
Objects are a way of building complex data structures and "building inside" code to "do things" in a data structure.
So, you have to 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" with:
use strict;
use warnings;
use MyMacro;
my $w = MyMacro->new();
$w->addtext("some text");
$w->addline();
$w->addtext("some text");
print $w ->flush;
It's pretty basic OOP, but you can get more advanced with Moose
.
+1
source to share