Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Print output file to a directory

by kcott (Archbishop)
on May 16, 2013 at 01:46 UTC ( [id://1033753]=note: print w/replies, xml ) Need Help??


in reply to Print output file to a directory

G'day Dr Manhattan,

Here's a working script followed by some notes.

[Due to the presence of UTF-8 characters, I've used <pre> blocks instead of <code> blocks.]

#!/usr/bin/env perl -l

use strict;
use warnings;
use utf8;
use autodie qw{:all};

use Cwd;
use File::Spec;

my $base_dir = getcwd();
my $new_dir = 'New Files';
my $out_file = 'NewTextFile.txt';
my $new_dir_path = File::Spec->catdir($base_dir, $new_dir);
my $output_path = File::Spec->catfile($new_dir_path, $out_file);
my $test_string = 'Greek letters: α ... ω';

mkdir $new_dir_path;
open my $output_fh, '>:utf8', $output_path;
print $output_fh $test_string;
close $output_fh;
use utf8;

You should use the utf8 pragma if your source contains UTF-8 characters. With my code as it is, I get this output:

$ cat 'New Files/NewTextFile.txt'
Greek letters: α ... ω

Without "use utf8;", I get:

$ cat 'New Files/NewTextFile.txt'
Greek letters: α ... Ï
use autodie qw{:all};

There are multiple points of potential failure (mkdir, open, print, close). Rather than attempting to identify each one and then hand-crafting appropriate "... or die ..." code for them, let Perl do this for you with the autodie pragma.

use Cwd;

Unless given an absolute path, mkdir will create the directory relative to the current working directory; not relative to the script directory (e.g. calling "../script.pl" from "script_dir/sub_dir" will create the new directory in "script_dir/sub_dir"; not in "script_dir"). You can use Cwd if you want that behaviour; of course, you may want different behaviour.

use File::Spec;

I don't know what platform you're on. You may want to run this code on multiple platforms. File::Spec provides portable file name operations.

open my $output_fh, '>:utf8', $output_path;

I've retained the 3-argument form of open but I've used a lexical variable for the filehandle. This is to avoid collisions with global filehandles that might have been used elsewhere in your code (e.g. OUTPUT) or confusion with known, existing barewords (e.g. O).

-- Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1033753]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-25 16:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found