it's easy enough. Just do like this:
#!/usr/bin/env perl
mkdir "New Files";
open O, ">New Files/NewTextFile.txt" or die "Can't: $!";
print O "Hi there\n";
| [reply] [d/l] |
Oh, oh, and you of course can 'cd' there if you like:
mkdir "New Files";
chdir "New Files";
open O, ">NewTextFile.txt" or die "Can't: $!";
print O "Hi there\n";
| [reply] [d/l] |
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).
| [reply] [d/l] [select] |