AnyData
view release on metacpan or search on metacpan
lib/AnyData/Storage/File.pm view on Meta::CPAN
if ( $first_line ) {
@fields = ref($parser) =~ /Fixed/
? split /,/,$first_line
: $parser->read_fields($first_line);
}
# my @fields = $first_line
# ? $parser->read_fields($first_line)
# : ();
#print "<$_>" for @fields; print "\n";
return "CAN'T FIND COLUMN NAMES ON FIRST LINE OF '"
. $self->{file}
. "' : '@fields'" if "@fields" =~ /[^ a-zA-Z0-9_]/;
$parser->{col_names} = \@fields;
$self->{col_names} = \@fields;
$self->{col_nums} = $self->set_col_nums;
$self->{first_row_pos} = $fh->tell();
return( \@fields);
}
sub open_table {
my( $self, $parser, $file, $open_mode ) = @_;
my($newfile, $fh);
$file ||= '';
if ( $file =~ m'http://|ftp://' ) {
# die "wrong storage!";
$newfile = $file;
}
else {
($newfile,$fh) =
$self->open_local_file($file,$open_mode) if $file && !(ref $file);
}
$newfile ||= $file;
#die AnyData::dump($parser);
my $col_names = $parser->{col_names} || '';
# my @array = split(/,/,$col_names);
my @array;
@array = ref $col_names eq 'ARRAY'
? @$col_names
: split ',',$col_names;
my $pos = $fh->tell() if $fh;
my %table = (
file => $newfile,
open_mode => $open_mode,
fh => $fh,
col_nums => {},
col_names => \@array,
first_row_pos => $pos
);
for my $key(keys %table) {
$self->{$key}=$table{$key};
}
my $skip = $parser->init_parser($self);
if (!$skip && defined $newfile) {
$open_mode =~ /[co]/
? $self->print_col_names($parser)
: $self->get_col_names($parser);
}
$self->{col_nums} = $self->set_col_nums();
# use Data::Dumper; die Dumper $self;
}
sub get_file_handle { return shift->{fh} }
sub get_file_name { return shift->{file} }
sub get_file_open_mode { return shift->{open_mode} }
sub file2str { return shift->get_record(@_) }
sub get_record {
my($self,$parser)=@_;
local $/ = $parser->{record_sep} || "\n";
my $fh = $self->{fh} ;
my $record = $fh->getline || return undef;
$record =~ s/\015$//g;
$record =~ s/\012$//g;
return $record;
}
sub set_col_nums {
my $self = shift;
my $col_names = $self->{col_names};
return {} unless $col_names;
my $col_nums={}; my $i=0;
for (@$col_names) {
next unless $_;
$col_nums->{$col_names->[$i]} = $i;
$i++;
}
return $col_nums;
}
sub truncate {
my $self = shift;
if (!$self->{fh}->truncate($self->{fh}->tell())) {
die "Error while truncating " . $self->{file} . ": $!";
}
}
sub drop ($) {
my($self) = @_;
# We have to close the file before unlinking it: Some OS'es will
# refuse the unlink otherwise.
$self->{'fh'}->close() || die $!;
unlink($self->{'file'}) || die $!;
return 1;
}
sub close{ shift->{'fh'}->close() || die $!; }
sub push_row {
my $self = shift;
my $rec = shift;
my $fh = $self->{fh};
#####!!!! DON'T USE THIS #### $fh->seek(0,2) or die $!;
$fh->write($rec,length $rec)
|| die "Couldn't write to file: $!\n";
}
sub delete_record {
my $self = shift;
my $parser = shift || {};
my $fh = $self->{fh};
my $travel = length($parser->{record_sep}) || 0;
( run in 0.637 second using v1.01-cache-2.11-cpan-39bf76dae61 )