lib::with::preamble initial import
[p5sagit/lib-with-preamble.git] / lib / lib / with / preamble.pm
1 package lib::with::preamble;
2
3 use strict;
4 use warnings FATAL => 'all';
5 use File::Spec;
6 use PerlIO::via::dynamic;
7
8 sub require_with_preamble {
9   my ($arrayref, $filename) = @_;
10   my (undef, $preamble, @libs) = @$arrayref;
11   foreach my $cand (map File::Spec->catfile($_, $filename), @libs) {
12     if (-f $cand) {
13       if (open my $fh, '<', $cand) {
14         return with_preamble($preamble."\n#line 1 $cand\n", $fh);
15       }
16     }
17   }
18 }
19
20 sub with_preamble {
21   my ($preamble, $fh) = @_;
22   PerlIO::via::dynamic->new(untranslate => sub {
23     $preamble and $_[1] =~ s/\A/$preamble/, undef($preamble);
24   })->via($fh);
25   return $fh;
26 }
27
28 sub import {
29   my ($class, $preamble, @libs) = @_;
30   return unless defined($preamble) and @libs;
31   unshift @INC, [ \&require_with_preamble, $preamble, @libs ];
32 }
33
34 1;