Thursday, 24 June 2010

File::Spit

John in my office a couple of days ago said we need the function 'spit' for writing to files much like we have 'slurp' in Perl6 (or by using one of my 3 fave cpan module Perl6::Slurp)

Since I have just had a couple of hours, I have just done this. File::Spit exports automatically the symbol 'spit'.


This method takes a file_path, $data and an optional delimiter flag.

From the POD:

spit:

will croak if once it has a file_path and a possible delimiter, it finds no data (note, this is different from an empty string or 0)

delimiter - if the delimiter matches against /\A[\s:=,.\/;]+\z/xms, it will be used, else it will just append to the file
perl false values (undef, q{} or 0) will be classified as though there is no delimiter given

will croak if it fails to write, with value of $EVAL_ERROR

Write to file, killing any previous versions of file (note, no warnings)

eval {
spit ( $FilePath, $data );
} or do {
your error handling here...
};

Append to file, creating if needed, but no delimiter

eval {
spit ( $FilePath, $string, 1 ); # note, it is just a true value, any perl false values will use write and kill previous file
} or do {
your error handling here...
};

Append as above, but with delimiter

eval {
spit ( $FilePath, $string, qq{\n\n} );
} or do {
your error handling here...
};

On success, this returns a true value (1)

This is probably completely unnecessary, or already exists on CPAN. If it doesn't, I'm happy to push to it, but for now, you can get it from github

http://github.com/setitesuk/File--Spit/tree/v0.1

This in theory could work with any type of data, but the tests only check strings.

I'm off on holiday now.

Happy Coding

Andy

2 comments:

Steven Haryanto said...

I never use Perl6::Slurp (and btw, it's last updated in 2004).

I use File::Slurp instead, and it has slurp() (or read_file()) as well as write_file().

write_file() has several options, e.g. error behaviour (whether to die or be silent on error), append mode, etc.

Andy Brown - SetitesUK said...

Hi Steven,

Thanks for that. I'll check it out.

Andy