Subroutine for reading and writing files from a single-user
script when no file locking is required.
usage:
@array = io('read',$file)
$string = io('read',$file)
io('write',$file,$string)
io('write',$file,\@array)
io('write',$file,$ref,'name') # Data::Dumper
Updated with grinder's improvements.
Added the dump line.
sub io
{
# usage:
# @array = io('read',$file)
# $string = io('read',$file)
# io('write',$file,$string)
# io('write',$file,\@array)
# io('write',$file,$ref,'name')
my($bit,$file,$data) = @_;
if($bit eq 'read'){
open IO,"< $file" or die "Cannot open $file for input: $!\n";
my@file = <IO>;
close IO;
wantarray ? return @file : return join '', @file;
}
if($bit eq 'write'){
open IO,"> $file" or die "Cannot open $file for output: $!\n";
print IO $data unless ref $data || $name;
print IO @$data if ref $data eq 'ARRAY';
# print IO Data::Dumper->new([$data],[$name])->Indent(2)->Quotekeys(
+0)->Dump if $name;
close IO;
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.