tags:

views:

88

answers:

5

The following script print some characters.

how to print the characters to file ( for example /var/tmp/file )

Yael

#!/usr/bin/perl 


@myNames = ('one', 'two', 'three' , 'A' , 'B' , 'C' , 'D' , 'E');

foreach (@myNames) {

print "$_\n";

} 
A: 
#!/usr/bin/perl 


@myNames = ('one', 'two', 'three' , 'A' , 'B' , 'C' , 'D' , 'E');

open(OUT,">","/var/tmp/file") or die "Could not open the output file: $!";

foreach (@myNames) {

print OUT "$_\n";

} 

close(OUT);
Vijey
THXin which cases we can get the "Could not open the output file"Yael
yael
One reason could be the target output file might be locked by some other process. In such cases, the program gets terminated with this error message
Vijey
@yael: when there's an error.
ysth
Use lexical filehandles, not globals. And you are missing `use strict; use warnings;`.
Ether
A: 
open FILE, ">filename"
print FILE "text"
knittl
after open you should close the file too!
Erik
oh c'mon … (yadayada)
knittl
+2  A: 

When you run the script, you can simply redirect the output to a file:

$ ./myscript.pl > /var/tmp/file
orangeoctopus
A: 
open(FILE, ">/var/tmp/file") || die "File not found";
print FILE @myNames;
close(FILE);
Erik
who ever set a negative vote here - please explain!
Erik
it wasn't me, but probably because you used a bareword file handle rather than a lexical, and you are not using the three argument open. `open my $file, '>', '/var/tmp/file' or die "error opening file: $!";`
Eric Strom
well, as long as this example is still in the official perldoc (Perl 5 version 12.1 documentation: http://perldoc.perl.org/ ), there is nothing wrong with it I think. So who ever is playing around with negative votes seems to be a know-it-all, that isn't able to read the official documentation.
Erik
A: 
#!/usr/bin/env perl
use strict;
use warnings FATAL => 'all';
use autodie qw(:all);

my @names = qw(one two three A B C D E);

{
    open my $fh, '>', '/var/tmp/file';
    foreach (@names) {
        print {$fh} "$_\n";
    }
}
daxim