in reply to Writing the contents of an array to a file

context has bitten me before.

it's been suggested that to avoid context problems, use something like this:

my $text = join(' ', @file2);

then print $text to the file.

i had a similar problem yesterday with a textarea in a CGI script i was writing yesterday. the join fixed it.

UPDATE: the scoping is also a problem. i just looked again. @file2 should be declared outside of the block. try a use vars qw/ @file2 / or declare @file2 outside of the while loop.

UPDATE 2: OK - the scoping was the issue, and  join is a bit of overkill. :)

Replies are listed 'Best First'.
RE: RE: Writing the contents of an array to a file
by chromatic (Archbishop) on Sep 28, 2000 at 23:47 UTC
    print invokes list context:
    [firewheel ~]$ perl my @list = (1 .. 4); print STDOUT @list;
    I prefer something like print STDOUT "@list";, which is semantically equivalent to print STDOUT (join($", @array));

    Fastolfe is correct, though. This is a scoping issue.

      FYI, $" is to print "@list" as $, is to print @list or print $a, $b, $c
      @a = qw{ one two }; @b = qw{ tre for }; { local $" = "-"; print "@a @b"; # one-two tre-for } { local $, = "-"; print @a, @b; # one-two-tre-for local $" = ":"; print "@a", "@b"; # one:two-tre:for }
      Cheers

        Note also that while each pair of lines of code below produce the same output:

        print FILE "@array"; print FILE join $", @array; print FILE @array; print FILE join $,, @array;
        they are not equivalent in terms of performance. Only print FILE @array avoids building a potentially huge string in memory before writing. In practice, the speed improvement is usually small (or even negative) but I prefer to allow for huge arrays and avoid the join if I'm just going to write the result to a file and then throw the constructed string away.

        Though I do find appealing the way that using join prevents your code from breaking if you accidentally sneak a scalar context into the mix (typing a "." when you meant a ",", for example).

                - tye (but my friends call me "Tye")
RE: RE: Writing the contents of an array to a file
by Fastolfe (Vicar) on Sep 28, 2000 at 23:46 UTC
    In this case, a join is unnecessary (but still perhaps valuable for others that need to do similar acts in the future):
    @a = (1, 2, 3); print @a; print $a[0], $a[1], $a[2]; # equivalent to @a
    Passing arguments to a function (even internal) as an array is just like passing a list of your own individual arguments. In this case, however, each element will be printed one after another. If you want to separate with spaces, either set $, or use join as you've done.

    If you're working from a list generated from a file, though, as we are here, newlines are still at the end of each element in the list, so printing them out like he's doing will have the desired effect:

    @list = <INPUT_FILE>; print OUTPUT_FILE @list; # exact (textual) copy