I was reading some old posts and came across TMTOWTDI... and most of them are wrong again. I saw that I disagreed with it at the time, and it got me thinking - how many ways really are there to do something? Thus, this challenge.
How many ways can we come up with to open a file?
I'm purposefully leaving this somewhat vague because there are many aspects to perl and the problems we try to solve. Bonus points for explaining the pros and cons of your approach. And bonus points for obscurity. Part of the excersise is to broaden our minds and escape the boxes we've grown accustomed to. We'll assume that $rfile is a filename relative to the current working directory or $afile is a filename with an absolute path - which you use is up to you.
To start things off, here is the trivial, fairly obvious case:
open my $fh, $rfile, 'r';
We get the advantages of a lexical filehandle, in an explicit mode, and should be able to handle spaces in the filename, or other wierd characters. We can be pretty assured that it will ignore special characters, such as < or | that may have been passed in. On the other hand, we can't handle those special characters transparently, such as when an advanced user wants to actually have us read from a pipe instead of a file.
Or, a more obscure case:
use File::Basename; use Net::FTP; my $ftp = Net::FTP->new('localhost'); $ftp->login($user, $password); $ftp->cwd(dirname($apath)); $ftp->binary(); my $dataconn = $ftp->retr(basename($apath));
The $dataconn object can be used like this:
my $data; while ($dataconn->read(my $buffer, 1024)) { $data .= $buffer; } print $data;
Advantage: none, I'm going for the obscure bonus points here. ;-) Well, that's not entirely true - this was actually quite enlightening to write and test on how to use Net::FTP to grab a file that I do not actually want to save to disk under its current name or even under any name. Disadvantage: really obscure for local files. A lot more code than is needed, plus the overhead of an FTP server that needs to be running.
I haven't covered the vast majority of trivial cases, but will let others do so. Also, if you have comments about pros/cons of any example, especially mine, please add that.
In reply to TIMTOWTDI Challenge: Open a file by Tanktalus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |