The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

edit_file

This sub writes out an entire file in one call.

  write_file( 'filename', @data ) ;

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.

  write_file( 'filename', {append => 1 }, @data ) ;
  write_file( 'filename', {binmode => ':raw'}, $buffer ) ;

As a shortcut if the first data argument is a scalar or array reference, it is used as the only data to be written to the file. Any following arguments in @_ are ignored. This is a faster way to pass in the output to be written to the file and is equivalent to the buf_ref option of read_file. These following pairs are equivalent but the pass by reference call will be faster in most cases (especially with larger files).

  write_file( 'filename', \$buffer ) ;
  write_file( 'filename', $buffer ) ;

  write_file( 'filename', \@lines ) ;
  write_file( 'filename', @lines ) ;

If the first argument is a handle (if it is a ref and is an IO or GLOB object), then that handle is written to. This mode is supported so you spew to handles such as \*STDOUT. See the test handle.t for an example that does open( '-|' ) and child process spews data to the parent which slurps it in. All of the options that control how the data are passed into write_file still work in this case.

If the first argument is an overloaded object then its stringified value is used for the filename and that file is opened. This is new feature in 9999.14. See the stringify.t test for an example.

By default write_file returns 1 upon successfully writing the file or undef if it encountered an error. You can change how errors are handled with the err_mode option.

The options are:

binmode

If you set the binmode option, then its value is passed to a call to binmode on the opened handle. You can use this to set the file to be read in binary mode, utf8, etc. See perldoc -f binmode for more.

        write_file( $bin_file, {binmode => ':raw'}, @data ) ;
        write_file( $bin_file, {binmode => ':utf8'}, $utf_text ) ;

perms

The perms option sets the permissions of newly-created files. This value is modified by your process's umask and defaults to 0666 (same as sysopen).

NOTE: this option is new as of File::Slurp version 9999.14;