3 ms·
Code like this: open my $fh, ">$file" or die "..."; will append to target if $file contains ">target". Code like this: open my $fh, '>', $file or die
by phaylon 16y ago
Code like this:
open my $fh, ">$file" or die "...";
will append to target if $file contains ">target". Code like this:
open my $fh, '>', $file or die "...";
explicitly tells Perl what the mode and what the filename is, so there can't be any confusion.
Using lexicals instead of typeglobs means you store the filehandle in a lexical variable instead of making it globally accessible in your package.
- Xurinos 16y agoAnd ultimately, wouldn't this be even more "modern", even clearer? -- my $file_path = Path::Class::dir("some_path")->file("file_name"); my $fh = $file_path->openw(); $fh->print("my line\n"); $fh->close(); Or for reading the whole file quickly, instead of the @var = <FILE> idiom -- my @var = $file_path->slurp();
- phaylon 16y agoIt can be, of course. There is more than one way to do it, because there's more than one situation in which one wants to use it. Most of my larger projects use Path::Class, but none of my scripts in ~phaylon/bin do, since I want to use some of them even if I don't have a perl setup yet. Another reason might be that you're writing a CPAN module and don't do much with files. If you just use it to write a debug log when an environment variable is set, you might not want to include another dependency. What your code demonstrates very good in my opinion is the fact that lexical filehandles are just more interoperable. You can pass them around transparently like any other reference, use modules that pass them around, and so on.