package File::Rewrite;

use strict;
use warnings;
use 5.010;  # smart match

use autodie ':all';
use Exporter 'import';

our $VERSION = '1.00';
our @EXPORT_OK = qw(fileset);

sub fileset {
	my ($filename, $search, $replace) = @_;
	my $tmpname = "$filename.$$.tmp";
	my $changes = 0;

	$replace = $search if @_ < 3;

	open my $src,  '<', $filename;
	open my $dest, '>', $tmpname;
	while (readline $src) {
		chomp;
		if ($_ ~~ $search) {
			if (ref $replace eq 'ARRAY') {
				if (@$replace and $_ eq $replace->[0]) {
					shift @$replace;
				}
				else {
					$changes++;
					next;
				}
			}
			elsif (defined $replace and $_ eq $replace) {
				undef $replace;
			}
			else {
				$changes++;
				next;
			}
		}
		print {$dest} $_, $/;
	}
	close $src;
	if (defined $replace) {
		for (ref $replace eq 'ARRAY' ? @$replace : $replace) {
			$changes++;
			print {$dest} $_, $/;
		}
	}
	close $dest;

	if ($changes) {
		rename $tmpname, $filename;
	}
	else {
		unlink $tmpname;
	}
	return $changes;
}

1;

=head1 NAME

File::Rewrite - Append and/or strip lines from text files

=head1 SYNOPSIS

	use File::Rewrite 'fileset';
	fileset('/tmp/somefile', qr/match/ => undef);

=head1 DESCRIPTION

=head1 AUTHOR

Mischa POSLAWSKY <perl@shiar.org>

=head1 LICENSE

Copyright. All rights reserved.

