in reply to efficient Array printing to a file

foreach $x (@x) { open ($x, ">>$log") or die; print while (<$x>); printf "%7d",$x; } close ($x);

Your code doesn't make a whole lot of sense; you appear to be using $x for more than one thing, and it's probably going to lead to problems. I'm not sure how this code can be working as you say it is. I will attempt to explain.

You say you want to append the elements of an array, @x to your file, $log. This means @x is filled with strings, perhaps long, perhaps short. You then iterate over them (foreach $x (@x)) and open a handle (open($x, ">>$log")) based on the string in @x. This means, if @x = ('foo bar baz', 'STDIN') you just opened the filehandles foo bar baz and STDIN. The STDIN example is an important one, as it illustrates the problem with this logic; by opening it, you just closed the STDIN you already had open. This same concept applies to any filehandle you may have open in your script. Also, this method of opening a filehandle is a symbolic reference, which is disallowed under use strict. You are using strict, right?

Once you've opened your file for appending you then go on to read from it (print while (<$x>)). You cannot read from a file opened for appending, and given what you're trying to do, I'm not sure why you're trying. I think you intended to print $x to the filehandle $x; there is a better way to do this, and I will cover it further down.

Finally, you close $x, but you do it outside of the foreach loop. At that point $x is undefined; you should have seen a warning about attempting to close undef; you are using warnings, right?

Now, as I mentioned, there is a much easier way to do this. You say you want to append the contents of @x to $log, and format each element with %7d:

open(my $logfh, ">>$log") || die("Unable to open log file \"$log\": \l$!.\n"); print $logfh join(" ", map { sprintf "%7d" $_ } @x); close($logfh);

I specifically used $logfh like that to illustrate a point; if you're opening a filehandle in a loop or other block, you don't need to use some random string (such as what's in $x).

Replies are listed 'Best First'.
Re: Re: efficient Array printing to a file
by Anonymous Monk on May 28, 2004 at 03:58 UTC
    Hi I understand what you are saying here...but my code works too.....hmm ... but the line print $logfh join(" ", map { sprintf "%7d" $_ } @x); is erroring out
      print $logfh join(" ", map { sprintf "%7d", $_ } @x)

      Note the comma after sprintf's format and $_. It was not in my original code. Also, that does not print a newline, which may be important.

        Hi again, What am i doing wrong here?? print FILE join(" ", map { sprintf "%7d", $_ } @x);