简体   繁体   中英

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?

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

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.

为什么不使用STDOUT重定向?

# perl yourscript.pl > yourfile.txt

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM