package File::Rewrite;

use strict;
use warnings;

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

our @EXPORT_OK = qw(fileset);

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

	open my $src,  '<', $filename;
	open my $dest, '>', $tmpname;
	while (readline $src) {
		if ($_ =~ (ref $search ? $search : qr/^\Q$search\E$/)) {
				$changes++;
				next;
		}
		print {$dest} $_, $/;
	}
	close $src;
	close $dest;

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

1;

=head1 NAME

File::Rewrite

=head1 SYNOPSIS

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

=head1 DESCRIPTION

=head1 AUTHOR

Mischa POSLAWSKY <perl@shiar.org>

=head1 LICENSE

Copyright. All rights reserved.

