G Nagasri Varma has asked for the wisdom of the Perl Monks concerning the following question:

I have to take the User Inputs from console and redirect the output to a text in perl. How can this be achieved.

EG :

open STDOUT, ">>", "output_cal_date.txt" or die "$0: open : $!";
$currenttime=localtime();
print "Current Time : $currenttime\n\n";
close STDOUT;

print ("Enter the FROM date in dd/mm/yyyy format : \n");
$from_date_1 =<STDIN>;
chomp($from_date_1);

I have tried using open STDOUT, but here in this case , It should pop up on cosole for user to enter the from date. But it is redirecting to a file.
Kindly help.
  • Comment on Take the input from command line and have output redirected to a file?

Replies are listed 'Best First'.
Re: Take the input from command line and have output redirected to a file?
by stevieb (Canon) on Dec 16, 2015 at 17:21 UTC

    It doesn't appear that you need to redirect STDOUT in this case. You can open a file handle, and then print directly to it:

    use warnings; use strict; open my $wfh, ">>", "output_cal_date.txt" or die "$0: open : $!"; my $currenttime = localtime(); print $wfh "Current Time : $currenttime\n\n"; # prints to file print "this prints to STDOUT"; print ("Enter the FROM date in dd/mm/yyyy format : \n"); my $from_date_1 = <STDIN>; chomp($from_date_1); print $wfh $from_date_1; close $wfh;
Re: Take the input from command line and have output redirected to a file?
by GotToBTru (Prior) on Dec 16, 2015 at 17:06 UTC

    By opening STDOUT in that manner, you have told it to direct output to that file, output_cal_date.txt, but only while it is open. Close it only after you have printed what you want to print.

    Dum Spiro Spero