5

It's possible to white a file utf-8 encoded as follows:

open my $fh,">:utf8","/some/path" or die $!;

How do I get the same result with IO::File, preferably in 1 line? I got this one, but does it do the same and can it be done in just 1 line?

my $fh_out = IO::File->new($target_file, 'w');
$fh_out->binmode(':utf8');

For reference, the script starts as follows:

use 5.020;
use strict;
use warnings;
use utf8;
# code here
capfan
  • 817
  • 10
  • 26

3 Answers3

4

Yes, you can do it in one line.

open accepts one, two or three parameters. With one parameter, it is just a front end for the built-in open function. With two or three parameters, the first parameter is a filename that may include whitespace or other special characters, and the second parameter is the open mode, optionally followed by a file permission value.

[...]

If IO::File::open is given a mode that includes the : character, it passes all the three arguments to the three-argument open operator.

So you just do this.

my $fh_out = IO::File->new('/some/path', '>:utf8');

It is the same as your first open line because it gets passed through.

Community
  • 1
  • 1
simbabque
  • 53,749
  • 8
  • 73
  • 136
4

I would suggest to try out Path::Tiny. For example, to open and write out your file

use Path::Tiny;

path('/some/path')->spew_utf8(@data);

From the docs, on spew, spew_raw, spew_utf8

Writes data to a file atomically.   [ ... ]
spew_raw is like spew with a binmode of :unix for a fast, unbuffered, raw write.

spew_utf8 is like spew with a binmode of :unix:encoding(UTF-8) (or PerlIO::utf8_strict ). If Unicode::UTF8 0.58+ is installed, a raw spew will be done instead on the data encoded with Unicode::UTF8.

The module integrates many tools for handling files and directories, paths and content. It is often simple calls like above, but also method chaining, recursive directory iterator, hooks for callbacks, etc. There is error handling throughout, consistent and thoughtful dealing with edge cases, flock on input/ouput handles, its own tiny and useful class for exceptions ... see docs.

zdim
  • 64,580
  • 5
  • 52
  • 81
-1

Edit: You could also use File::Slurp if it was not discouraged to use

e.g

use File::Slurp qw(write_file);

write_file( 'filename', {binmode => ':utf8'}, $buffer ) ;

The first argument to write_file is the filename. The next argument is an optional hash reference and it contains key/values that can modify the behavior of write_file. The rest of the argument list is the data to be written to the file.

Some good reasons to not use?

Community
  • 1
  • 1
carlosn
  • 423
  • 3
  • 9