Source

perl-begin / src / topics / files-and-directories / index.html.wml

Shlomi Fish 357d51c 
Shlomi Fish 1f44c2e 
Shlomi Fish a90a1e5 
Shlomi Fish 357d51c 
Shlomi Fish ba7b212 


Shlomi Fish 09b0f0e 
Shlomi Fish ba7b212 

Shlomi Fish 357d51c 




Shlomi Fish 67b89ea 
Shlomi Fish 357d51c 


Shlomi Fish 1f44c2e 



Shlomi Fish 357d51c 


Shlomi Fish 34073a9 


Shlomi Fish 357d51c 





Shlomi Fish a90a1e5 
Shlomi Fish 357d51c 
Shlomi Fish ba7b212 









Shlomi Fish 9f57915 


Shlomi Fish 17744ce 

Shlomi Fish ba7b212 


Shlomi Fish 9f57915 






Shlomi Fish 7e2eae1 
Shlomi Fish ba7b212 








Shlomi Fish 721f27f 


Shlomi Fish 7a07c67 


Shlomi Fish ea64ca5 

Shlomi Fish 3acfd44 
Shlomi Fish 6a37850 
Shlomi Fish d7385cf 
Shlomi Fish ea64ca5 


Shlomi Fish d7385cf 
Shlomi Fish 1f147a6 
Shlomi Fish 3acfd44 






Shlomi Fish ba7b212 


Shlomi Fish 7e2eae1 
Shlomi Fish 3acfd44 
Shlomi Fish ba7b212 
Shlomi Fish 3acfd44 




Shlomi Fish ba7b212 




Shlomi Fish 3acfd44 



Shlomi Fish d7385cf 
Shlomi Fish 331c800 
Shlomi Fish ea64ca5 
Shlomi Fish 54610b9 
Shlomi Fish d7385cf 

Shlomi Fish ce600ab 
























Shlomi Fish 54610b9 
Shlomi Fish ce600ab 
Shlomi Fish ea64ca5 
Shlomi Fish 54610b9 
Shlomi Fish d7385cf 

Shlomi Fish 0dff951 
























































Shlomi Fish 54610b9 
Shlomi Fish 0dff951 
Shlomi Fish ea64ca5 
Shlomi Fish 54610b9 
Shlomi Fish d7385cf 

Shlomi Fish 721f27f 





Shlomi Fish 4c75112 

Shlomi Fish ce600ab 
Shlomi Fish 721f27f 
Shlomi Fish 4c75112 
Shlomi Fish 721f27f 




Shlomi Fish 4c75112 

Shlomi Fish 22b45ea 



Shlomi Fish 02acb9f 
Shlomi Fish 22b45ea 









Shlomi Fish ce600ab 











Shlomi Fish 54610b9 
Shlomi Fish 22b45ea 
Shlomi Fish ea64ca5 
Shlomi Fish 54610b9 
Shlomi Fish d7385cf 

Shlomi Fish ce600ab 





Shlomi Fish b6c1080 




Shlomi Fish ce600ab 
Shlomi Fish b6c1080 
Shlomi Fish ce600ab 




Shlomi Fish b6c1080 








Shlomi Fish ce600ab 


Shlomi Fish 7a07c67 

Shlomi Fish 0abb84f 


































































Shlomi Fish b0a58e7 



























Shlomi Fish 0abb84f 
Shlomi Fish 89dc764 










































Shlomi Fish 7a07c67 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#include '../template.wml'
#include "xhtml/1.x/std/toc.wml"
#include "files_dirs_modules.wml"

<page_extra_head_elements>
<script type="text/javascript" src="$(ROOT)/js/jquery-ui-1.9.2.custom.min.js"></script>
<link rel="stylesheet" type="text/css" href="$(ROOT)/css/smoothness/jquery-ui-1.9.2.custom.min.css" media="screen, projection" />
<link rel="stylesheet" type="text/css" href="$(ROOT)/jqui-override.css" media="screen, projection" />
</page_extra_head_elements>

<latemp_subject "Files and Directories Handling in Perl" />

<p>
Perl has strong support for handling files and directories, which are the
bread-and-butter of dealing with the disk and the filesystem. Many modules
on <a href="$(ROOT)/topics/cpan/">CPAN (= the Comprehensive Perl Archive Network)</a>
aim to facilitate the task even further.
</p>

<h2* id="toc">Table of Contents</h2*>

<toc />

<h2 id="basics">The Basics</h2>

<p>
For the basics, read about the open function (on
<pdoc d="perlopentut"></pdoc> or
on <a href="$(ROOT)/resources/">recommended books or tutorials</a>) as well as
other built-ins such as
<pdoc_f f="opendir">opendir</pdoc_f>, <pdoc_f f="readdir">readdir</pdoc_f>,
<pdoc_f f="closedir">closedir</pdoc_f>, <pdoc_f f="mkdir">mkdir</pdoc_f>. There
are also many UNIX-oriented file-system-builtins listed on <pdoc d="perlfunc"></pdoc> which may prove of utility.
</p>

<files_and_directories_modules />

<h2 id="examples">Examples</h2>

<p>
These are a set of examples for manipulating files and directories using Perl.
Each will be shown in several versions including ones using IO-All, ones using
core modules, and if relevant ones from the command line.
</p>

<define-tag perl_code endtag="required">
<pre class="perl">
<:{
    use Text::VimColor;

    my $sh_bang = qq{#!/usr/bin/perl\n\n};
    my $s = $sh_bang . <<'EOF_BLAH_BLAH_YES_THIS_IS_PERL_CODE_TO_PASS_TO_VIM';
use strict;
use warnings;
%body
EOF_BLAH_BLAH_YES_THIS_IS_PERL_CODE_TO_PASS_TO_VIM

    my $tvc = Text::VimColor->new(
        string => \$s,
        filetype => 'perl',
    );
    print $tvc->html() =~ s{(class=")syn}{$1}gr;
}:>
</pre>
</define-tag>

<script type="text/javascript">
    $(function() {
        $(".tabs").tabs();
    });
</script>

<:
    use PerlBegin::TopicsExamples;

    use strict;
    use warnings;

    # Examples generator:
    my $ex_gen = PerlBegin::TopicsExamples->new(
        {
            default_syntax => 'perl',
        }
    );

    print $ex_gen->html_with_title(
        {
            title => "Copying a file",
            id_base => "copying_a_file",
            examples =>
            [
                {
                    id => "io_all",
                    label => "IO-All",
                    code => <<'EOF',
use IO::All;

my ($source_filename, $dest_filename) = @_;
io->file($source_filename) > io->file($dest_filename);
EOF

                },
                {
                    id => "core",
                    label => "Core Perl",
                    code => <<'EOF',
use File::Copy qw(copy);

my ($source_filename, $dest_filename) = @_;

copy($source_filename, $dest_filename);
EOF
                },
            ],
        }
    );

    print $ex_gen->html_with_title(
        {
            title => "Overwriting a file with text",
            id_base => "overwrite_a_file",
            examples =>
            [
                {
                    id => "io_all",
                    label => "IO-All",
                    code => <<'EOF',
use IO::All;

io->file("output.txt")->utf8->print("Hello World!\n");
EOF

                },
                {
                    id => "core",
                    label => "Core Perl",
                    code => <<'EOF',
use autodie;

open my $out, '>:encoding(utf8)', "output.txt";
print {$out} "Hello World!\n";
close($out);
EOF
                },
            ],
        }
    );

    print $ex_gen->html_with_title(
        {
            title => "Processing the Lines of a File",
            id_base => "processing_lines_of_a_file",
            examples =>
            [
                {
                    id => "file_slurp",
                    label => "File::Slurp",
                    code => <<'EOF',
use File::Slurp;

my @filenames = @ARGV;

foreach my $fn (@filenames)
{
    edit_file_lines sub { s/\bFrom\b/To/g }, $fn;
}
EOF

                },
                {
                    id => "core",
                    label => "Core Perl",
                    code => <<'EOF',
use autodie;
use File::Temp ( qw(tempfile) );

my @filenames = @ARGV;

foreach my $fn (@filenames)
{
    open my $in, '&lt;', $fn;
    my ($tempout, $temp_fn) = tempfile();

    while (my $line = &lt;$in&gt;)
    {
        chomp($line);
        \# Perform the operation here.
        $line =~ s/\bFrom\b/To/g;

        print {$tempout} "$new_line\n";
    }

    close($in);
    close($tempout);

    rename($temp_fn, $fn);
}
EOF
                },
                {
                    id => "cmd_line",
                    label => "Command Line",
                    no_syntax => 1,
                    code => <<'EOF',
$ perl -i.bak -lp -e 's/\bFrom\b/To/g' *.txt
EOF
                },
            ],
        }
    );

    print $ex_gen->html_with_title(
        {
            title => "Reading an entire UTF-8 file into a big variable",
            id_base => "string_slurp_utf8",
            examples =>
            [
                {
                    id => "io_all",
                    label => "IO-All",
                    code => <<'EOF',
use IO::All;

my $string = io->file($my_filepath)->utf8->slurp;
EOF

                },
                {
                    id => "core",
                    label => "Core Perl",
                    code => <<'EOF',
use autodie;

sub _utf8_slurp
{
    my $filename = shift;

    open my $in, '<:encoding(utf8)', $filename;

    local $/;
    my $contents = <$in>;

    close($in);

    return $contents;
}

my $file_contents = _utf8_slurp($my_filepath);
EOF
                },
                {
                    id => "cmd_line",
                    label => "Command Line",
                    no_syntax => 1,
                    code => <<'EOF',
$ perl -i.bak -ln -0777 -C -ln -e 'Something with $_ here' "$my_utf8_filepath"
EOF
                },
            ],
        }
    );

    print $ex_gen->html_with_title(
        {
            title => "Appending to a File",
            id_base => "append_to_file",
            examples =>
            [
                {
                    id => "io_all",
                    label => "IO-All",
                    code => <<'EOF',
use IO::All;

my $string_to_append = "My new line\n";

$string_to_append >> io->file($my_file_path);
EOF

                },
                {
                    id => "core",
                    label => "Core Perl",
                    code => <<'EOF',
use autodie;

my $string_to_append = "My new line\n";

{
    open my $out, '>>', $my_file_path;
    print {$out} $string_to_append;
    close($out);
}
EOF
                },
            ],
        }
    );

    print $ex_gen->html_with_title(
        {
            title => "Line count",
            id_base => "line_count",
            examples =>
            [
                {
                    id => "io_all",
                    label => "IO-All",
                    code => <<'EOF',
use IO::All;

sub count_lines
{
    my ($filename) = @_;

    my $fh = io->file($filename);

    my $count = 0;

    while (my $l = <$fh>)
    {
        $count++;
    }

    return $count;
}
EOF

                },
                {
                    id => "core",
                    label => "Core Perl",
                    code => <<'EOF',
use autodie;

sub count_lines
{
    my ($filename) = @_;

    open my $fh, '<', $filename;

    my $count = 0;
    while (my $l = <$fh>)
    {
        $count++;
    }

    close($fh);

    return $count;
}
EOF
                },
                {
                    id => "cmd_line",
                    label => "Command Line",
                    no_syntax => 1,
                    code => <<'EOF',
$ perl -lnE 'END{say "$ARGV has $. lines";}' /path/to/myfile.txt
EOF
                },
            ],
        }
    );

    print $ex_gen->html_with_title(
        {
            title => "Deleting a directory tree",
            id_base => "delete_directory_tree",
            examples =>
            [
                {
                    id => "io_all",
                    label => "IO-All",
                    code => <<'EOF',
use IO::All;

io("./path-to-subdir")->rmtree();
EOF

                },
                {
                    id => "core",
                    label => "Core Perl",
                    code => <<'EOF',
use File::Path qw(rmtree);

rmtree(["./path-to-subdir"], 1, 1);
EOF
                },
            ],
        }
    );

    print $ex_gen->html_with_title(
        {
            title => "Prepending to a File (While Slurping)",
            id_base => "prepend_to_file_while_slurping",
            examples =>
            [
                {
                    id => "io_all",
                    label => "IO-All",
                    code => <<'EOF',
use IO::All;

my $filename = 'foo.txt';
my $text_to_prepend = "[Text to Prepend]\n";

my $fh = io->file($filename);

$fh->print( $text_to_prepend . $fh->slurp() );
EOF

                },
                {
                    id => "core",
                    label => "Core Perl",
                    code => <<'EOF',
my $filename = 'foo.txt';
my $text_to_prepend = "[Text to Prepend]\n";

open my $in_fh, '<', $filename
    or die "Could not open file '$filename' for reading! - $!";
my $contents = do { local $/; <$in_fh>;};
close($in_fh);

open my $out_fh, '>', $filename
    or die "Could not open file '$filename' for writing! - $!";
print {$out_fh} $text_to_prepend . $contents;
close($out_fh);
EOF
                },
            ],
        }
    );

:>