open (FILE, "test.txt");
@file = <FILE>;
close (FILE);
$variable = @file[0]++;
-- The part above works, part below doesn't
open (FILE2, ">test.txt");
print FILE2 "$variable";
close(FILE2);
D O N
You could try separating the '>' from the filename, as per the following syntax:
open OUTPUT_FILE, '>', "text.txt" or LogErrorAndDie("Couldn't open output file: text.txt", __FILE__, __LINE__);
print OUTPUT_FILE "Some text";
with the function LogErrorAndDie defined somewhere as follows:
sub LogErrorAndDie
{
print "ERROR: File: $_[1], Line: $_[2]\n";
print "----> $_[0]\n";
exit 1;
}
If that doesn't work, I'd suggest checking you have the appropriate permissions on the file or directory you are trying to write to.
open HANDLE, '>', "filename"
works for me, your original syntax of
open HANDLE, ">filename"
is perfectly valid too.
Perhaps the problem is with what you are trying to print to the file. What is $variable set to before the print statement?
What are you trying to do with the statement:
$variable = @file[0]++;
$variable = $array[n]; sets variable to the nth element of the array
$variable = @array; sets variable to the size of the array
Not sure if $variable = @array[n]; is a reasonable thing to do.
$variable = @array[n]++;
should be written as
$variable = $array[n]++;
as Perl [perl.com] will tell you when it is run with warnings enabled (-w switch or use [perldoc.com] warnings [perldoc.com]).
But otherwise it is perfectly legal. It will assign the old value of $array[n] to $variable and then increase it by one.
Andreas
Even better yet put '.. or die "Could not open test.txt: $!" behind your opening statement. $! will contain the error message of what went wrong when Perl [perl.com] tried to open the file.
Andreas