| 1 | # $Id: /mirror/perl/Iterator-File-Line/trunk/lib/Iterator/File/Line.pm 42691 2008-02-25T01:07:47.310615Z daisuke $ | ||
| 2 | # | ||
| 3 | # Copyright (c) 2008 Daisuke Maki <daisuke@endeworks.jp> | ||
| 4 | # All rights reserved. | ||
| 5 | |||
| 6 | package Iterator::File::Line; | ||
| 7 | use strict; | ||
| 8 | use warnings; | ||
| 9 | use base qw(Class::Accessor::Fast); | ||
| 10 | |||
| 11 | our $VERSION = '0.00002'; | ||
| 12 | |||
| 13 | __PACKAGE__->mk_accessors($_) for qw(source filter chomp encoding eol); | ||
| 14 | |||
| 15 | sub new | ||
| 16 | { | ||
| 17 | my $class = shift; | ||
| 18 | my %args = @_; | ||
| 19 | |||
| 20 | if ( $args{filename} ) { | ||
| 21 | return $class->new_from_file( %args ); | ||
| 22 | } elsif ($args{fh}) { | ||
| 23 | return $class->new_from_fh( %args ); | ||
| 24 | } | ||
| 25 | |||
| 26 | die "Must provide filename or file handle"; | ||
| 27 | } | ||
| 28 | |||
| 29 | sub new_from_file | ||
| 30 | { | ||
| 31 | my $class = shift; | ||
| 32 | my %args = @_; | ||
| 33 | |||
| 34 | my $filename = delete $args{filename}; | ||
| 35 | open(my $fh, '<', $filename) or die "Could not open $filename"; | ||
| 36 | |||
| 37 | $class->new_from_fh( %args, fh => $fh ); | ||
| 38 | } | ||
| 39 | |||
| 40 | sub new_from_fh | ||
| 41 | { | ||
| 42 | my $class = shift; | ||
| 43 | my %args = @_; | ||
| 44 | my $fh = delete $args{fh}; | ||
| 45 | |||
| 46 | my $self = $class->SUPER::new( { | ||
| 47 | filter => $args{filter}, | ||
| 48 | chomp => exists $args{chomp} ? $args{chomp} : 1, | ||
| 49 | eol => $args{eol}, | ||
| 50 | encoding => $args{encoding}, | ||
| 51 | source => $fh, | ||
| 52 | } ); | ||
| 53 | |||
| 54 | $self->_setup_layers(); | ||
| 55 | return $self; | ||
| 56 | } | ||
| 57 | |||
| 58 | sub next | ||
| 59 | { | ||
| 60 | my $self = shift; | ||
| 61 | my $fh = $self->source; | ||
| 62 | my $line = <$fh>; | ||
| 63 | return undef unless defined $line; | ||
| 64 | chomp $line if $self->chomp; | ||
| 65 | return $self->filter ? $self->filter->( $line ) : $line; | ||
| 66 | } | ||
| 67 | |||
| 68 | sub rewind | ||
| 69 | { | ||
| 70 | my $self = shift; | ||
| 71 | my $fh = $self->source; | ||
| 72 | seek($fh, 0, 0); | ||
| 73 | } | ||
| 74 | |||
| 75 | sub _setup_layers | ||
| 76 | { | ||
| 77 | my $self = shift; | ||
| 78 | my $fh = $self->source; | ||
| 79 | |||
| 80 | my @layers = ('', 'raw'); | ||
| 81 | if ($self->eol) { | ||
| 82 | push @layers, sprintf('eol(%s)', $self->eol ); | ||
| 83 | } | ||
| 84 | |||
| 85 | if ($self->encoding) { | ||
| 86 | push @layers, sprintf('encoding(%s)', $self->encoding); | ||
| 87 | } | ||
| 88 | |||
| 89 | binmode($fh, join(':', @layers)); | ||
| 90 | } | ||
| 91 | |||
| 92 | 1; | ||
| 93 | |||
| 94 | __END__ |