For::Else - Else blocks for foreach


For-Else documentation Contained in the For-Else distribution.

Index


Code Index:

NAME

Top

For::Else - Else blocks for foreach

VERSION

Top

Version 0.01

SYNOPSIS

Top

	use For::Else;

	foreach my $item ( @items )
	{
		_do_something_with_item();
	}
	else
	{
		die "@items was empty";
	}

DESCRIPTION

Top

We usually iterate over a list like the following:

	foreach my $item ( @items )
	{
		_do_something_with_item();
	}

However, a lot of the time I find myself needing to accomodate for the exceptional case where the list is empty:

	if ( @items )
	{
		foreach my $item ( @items )
		{
			_do_something_with_item();
		}
	}
	else
	{
		die "@items was empty";
	}

Since we don't enter into a foreach block when there are no items in the list anyway, I find the if to be rather redundant. Wouldn't it be nice to get rid of it so we can do the following?

	foreach my $item ( @items )
	{
		_do_something_with_item();
	}
	else
	{
		die "@items was empty";
	}

Now you can!

DEPENDENCIES

Top

Filter::Simple

BUGS / FEATURES

Top

Note: Does not interpolate void-contextual expressions yet e.g. ranges, qw{}, etc.

Please report any bugs or features. Better yet, submit a patch :)

SEE ALSO

Top

Fur::Elise by Ludwig van Beethoven

AUTHOR

Top

Alfie John, alfie at hackfu.org

COPYRIGHT AND LICENCE

Top


For-Else documentation Contained in the For-Else distribution.

package For::Else;

use strict;
use warnings;

our $VERSION = q{0.02};

use Filter::Simple;

# Recursive regexp first pointed out to me in Acme::Butfirst (see perlre for
# extended patterns ). Acme:: is a land^H^H^H^Hgold mine!

my $parens_block;

$parens_block = qr{
		[(]
				(?>
						[^()]+ | (??{ $parens_block })
				)*
		[)]
}smx;

my $code_block;

$code_block = qr{
		{
				(?>
						[^{}]+ | (??{ $code_block })
				)*
		}
}smx;

FILTER_ONLY
	'code' => sub {
		1 while
			s{
								( for(?:each)? [^(]* ($parens_block) \s*
										$code_block )                    \s*
								( else                               \s*
										$code_block )
						}{
								if $2
								{
										$1
								}
								$3
						}smx;
	};

1;

__END__