Acme-ButFirst

 view release on metacpan or  search on metacpan

lib/Acme/ButFirst.pm  view on Meta::CPAN

$block = qr{
	{					# An open-curly
		(?:
			(?> [^{}]+ )		# Non-curlies no backtracking.
			|
			(??{ $block })		# An embedded block
		)*
	}					# Close-curly
}x;

sub _butfirstify {

	# Continue to re-write our code until no more butfirst
	# sections exist.

	# We enclose each pair of blocks transposed inside their
	# own block.  This allows chained but-firsts and
	# butfirst modifiers on loops to work 'correctly'.

	1 while s{ ($block) \s* but \s* first \s* ($block) }
                 {{$2\n$1}}gxs;

};

# We have to use 'executable' rather than code, as Filter::Simple
# sometimes thinks that 'but \s* first' is a bareword string.
#
# The downside of this is that we may modify some *real* strings
# as well as code.


FILTER_ONLY executable => \&_butfirstify;

1;
__END__

=head1 NAME

Acme::ButFirst - Do something, but first do something else.

=head1 SYNOPSIS

lib/Acme/ButFirst.pm  view on Meta::CPAN

		print "$count\n";
	} but first {
		print "I can count to...";
	}

	# Print our lines, but first reverse them, but first convert
	# them into upper case.

	while (<>) {
		print;
	} butfirst {
		$_ = reverse $_;
	} butfirst {
		$_ = uc $_;
	}

=head1 DESCRIPTION

C<Acme::ButFirst> allows you to execute a block of code, but first do
something else.  Perfect for when you wish to add to the start
of a long block of code, but don't have the energy to scroll
upwards in your editor.

C<Acme::ButFirst> recognises both C<butfirst> and C<but first> as
keywords.

Usage of C<Acme::ButFirst> is lexically scoped.  ButFirstification
can be explicitly disabled by using C<no Acme::ButFirst>.

=head1 SEE ALSO

L<http://lists.slug.org.au/archives/slug/2005/09/msg00346.html>

L<Acme::Dont::t>, L<Acme::ComeFrom>, L<Acme::Goto::Line>

t/02_simple.t  view on Meta::CPAN


use Acme::ButFirst;

sub simple {

	my $x = "";

	{
		$x .= "bar";
		$x .= "qux";
	} butfirst {
		$x .= "foo";
		$x .= "baz";
	}

	return $x;

}

our $z;

sub postsub {
	my $y = 1;

	$y = $y + $z;

	return $y;
	
} butfirst {
	$z = 5;
}

sub string_embed {
	return "{ milk } but first { coffee }";
}



( run in 0.238 second using v1.01-cache-2.11-cpan-4d50c553e7e )