Home > Archive > PERL Beginners > August 2007 > How to save input STDIN into a file
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
How to save input STDIN into a file
|
|
| Sydney 2007-08-06, 7:58 am |
| The script working fine. but I like to save output of "$avar="$dir/
$db" into a file. How do I do that? Thanks LC
print "which client\n";
my $a = <>;
chomp $a;
my $db = <>;
chomp $db;
my $dir="/u1/data/$a";
my $avar="$dir/$db";
$avar="$dir/$db";
print "$avar\n";
| |
| Paul Lalli 2007-08-06, 6:59 pm |
| On Aug 6, 2:16 am, cold1...@gmail.com (Sydney) wrote:
> The script working fine. but I like to save output of "$avar="$dir/
> $db" into a file. How do I do that? Thanks LC
perldoc perlopentut
perldoc -f open
perldoc -f print
Paul Lalli
| |
| Chas Owens 2007-08-06, 6:59 pm |
| On 8/6/07, Sydney <cold1man@gmail.com> wrote:
> The script working fine. but I like to save output of "$avar="$dir/
> $db" into a file. How do I do that? Thanks LC
>
>
> print "which client\n";
> my $a = <>;
> chomp $a;
> my $db = <>;
> chomp $db;
> my $dir="/u1/data/$a";
> my $avar="$dir/$db";
> $avar="$dir/$db";
>
> print "$avar\n";
To write to a file you need a file handle. To get a file handle you
should use the open function. You can get detailed information on the
open function by typing "perldoc -f open", but here is the basic form
you should use:
#!/usr/bin/perl
use strict;
use warnings;
print "which client\n";
chomp(my $dbdir = <> );
chomp(my $db = <> );
my $dir="/u1/data/$dbdir";
my $var="$dir/$db";
my $filename = "/tmp/foo.txt";
open my $fh, ">", $filename
or die "could not open $filename:$!";
print $fh "$var\n";
Things to note:
* $a is a special variable, it along with $b are used by the sort
function and should not be used outside of a sort block.
* you can chomp the variables as you assign to them
* there is no comma between $fh and "$var\n" (this is how print
knows it should use the $fh as a file handle instead trying to print
it's contents)
Things to think about :
* programs that ask questions are a pain in the rear, consider
changing this from reading STDIN to parsing command line arguments.
* unless there is some pressing reason to keep $dir and $var
separate, they should probably be joined into one variable.
* consider passing in the name of the file to write to on the
command line or reading it from a config file rather than hard coding
it like I do here.
|
|
|
|
|