io.pm
# io.pm # Copyright (c) 2004 Jan Henning Thorsen, all rights reserved # URL: http://eidolon.flodhest.net E-MAIL: [email protected] #============================================================================ package io; use strict; use Text::Template; #============================================================================ sub error { ### init my @caller = caller(1); my $message = "$caller[3]: ($caller[2]) '$_[0]'" || ""; ### write error to stderr #print STDERR $message; ### store error to cgi main::cgi()->append('_error', $message); ### the end return undef; } #============================================================================ sub opn { ### init local $_; my %args = ( _file => shift, map { $_ => 1 } split(/\,\s+/, shift) ); my @file = (); ### open file open(FH, $args{_file}) or return io::error(join ", ", $!, $args{_file}); ### single line if($args{oneline}) { local $/; $file[0] = <FH>; } ### multi line else { @file = <FH>; } ### close file close FH; ### chomp if($args{chomp}) { chomp @file; } ### the end return ($args{oneline}) ? $file[0] : @file; } #============================================================================ sub wrt { ### init my $data = pop; my %args = (@_ % 2) ? (_file => shift) : @_; ### fix mode $args{mode} = '>' unless($args{mode} =~ /\>/); ### write to the file open(FH, $args{mode}, $args{_file}) or return io::error(join ", ", $!, $args{mode}, $args{_file}); print FH (ref $data eq 'ARRAY' ? @{$data} : $data); close FH; ### the end return 1; } #============================================================================ sub template { ### init my $file; my %args; ### fix input if(@_ % 2) { $file = shift; } else { %args = @_; } ### check $ENV{TEMPLATE} or return io::error('$ENV{TEMPLATE} is not set'); -d $ENV{TEMPLATE} or return io::error("path $ENV{TEMPLATE} does not exist"); ### fix $args{_file} = "$ENV{TEMPLATE}/$args{_file}.html"; ### create template if(%args) { my $template = Text::Template->new( TYPE => "FILE", SOURCE => $args{_file}, ) or return io::error($Text::Template::ERROR); ### the end return $template->fill_in(HASH => \%args); } ### normal file else { return io::opn($args{_file}); } } #============================================================================ 1;