Loai
Loai

Reputation: 11

How do I use Perl to print to a text file?

I tried to create a word list starting with 0500000000 to 0600000000 with Perl code

#!/bin/perl -w
$k = 10;
$width = 10;
for $i ( 500000000 .. 600000000 ) {
    printf "%${width}.${k}ld\n", $i;
}

I need to print the result to a text file. Can anyone help?

Upvotes: 1

Views: 305

Answers (4)

Dan Straw
Dan Straw

Reputation: 231

Using filehandles. For instance:

#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';
use autodie qw(:all);

open my $FILE, '>', 'filename.txt';

my $k = 10;
my $width = 10;
for $i ( 500000000 .. 600000000 ) {
    printf {$FILE} "%${width}.${k}ld\n", $i;
}

close $FILE;

Use file mode > to truncate any existing file, or >> to append to it.

Upvotes: 4

grimmig
grimmig

Reputation: 1421

Why not use STDOUT redirection?

# perl yourscript.pl > yourfile.txt

Upvotes: 2

Sinan Ünür
Sinan Ünür

Reputation: 118118

$ perl -e 'print "$_\n" for "0500000000" .. "0600000000"' > output.txt

Upvotes: 5

justkt
justkt

Reputation: 14766

To print to a text file, read up on PerlIO. This will tell you how to open a handle to a file, print to that file, and close the handle when you are done.

Upvotes: 1

Related Questions