gam has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I want to create a file with the name thats passed from a variable. With the below code the file is not created. Here I want to create a file with the name testing.txt. Can some lemme know wer am I going wrong.
$testCase = "testing";
$command = "lin --help";
my $test = "/usr/anil/scripts/ActData/$testCase.txt";
open (STDERR, "> $test");
$t = system($command);

Replies are listed 'Best First'.
Re: Dynamically Create a file
by starX (Chaplain) on Aug 01, 2008 at 05:18 UTC
    I see a couple places you're going wrong. First and foremost, system() returns the exit status of the command, not the commands output. If you want the output of "lin --help", you should run it as qx/$command/. Of course, qx// doesn't pay attention to STDERR, so if you're interested in capturing that, you should re-write the command as $command = "lin --help 2> $test";

    2> is the shells way of redirecting STDERR to someplace else.

    Try this on for size...

    use strict; use warnings; $testCase = "testing"; my $test = "./$testCase.txt"; $command = "lin --help 2> $test"; my $result = `$command`; print $result;
    Note the use strict; and use warnings; directives. Those are your friend. EDIT: I should probably mention that I used qx// rather than system() because the former will return a program's output, and the latter only returns the return status.
Re: Dynamically Create a file
by Anonymous Monk on Aug 01, 2008 at 04:48 UTC
    #!/usr/bin/perl -T -- use strict; use warnings; my $testCase = 'testing'; my $command = 'lin --help'; my $test = sprintf "/usr/anil/scripts/ActData/%s.txt", $testCase; open (STDERR, ">", $test ) or die "couldn't create $test : $!"; $t = system($command);
    See perlopentut, perlsec, sprintf
Re: Dynamically Create a file
by jethro (Monsignor) on Aug 01, 2008 at 11:02 UTC
    I tried your script and testing.txt was created without problem.

    So either /usr/anil/scripts/ActData doesn't exist (spelling?) or it is not writable by you. Or this code path is never executed (in a supposedly bigger script).