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

Hello All,

When we print array elements to a file (please refer the code below), by default space character is placed as the delimiter between the array elements.

Is there a direct way/variable where we can specify the delimiter to separate the array elements.

#!/usr/bin/perl use strict; use warnings; open my $fh, '>', 'array.out' or die "Could not create the file.\n"; my @array = ('one','two','three','four','five'); print $fh "@array"; close $fh;

Replies are listed 'Best First'.
Re: Printing Array to a file
by Corion (Patriarch) on Jan 27, 2010 at 08:00 UTC

    Yes, there is, $". See perlvar.

    Also, it is good practise to limit all changes you make to $" to a small block by using local:

    { # output as tab delimited: local $" = "\t"; print $fh "@array\n"; } # $" has its old value here again
Re: Printing Array to a file
by chromatic (Archbishop) on Jan 27, 2010 at 08:02 UTC

    The global variable $" contains the separator, though it's often clearer to use join:

    use 5.010; # this has the same effect as... { local $" = ', '; say {$fh} @array; } # a shorter approach say {$fh} join ', ', @array;
Re: Printing Array to a file
by Ratazong (Monsignor) on Jan 27, 2010 at 08:00 UTC
Re: Printing Array to a file
by ambrus (Abbot) on Jan 27, 2010 at 09:46 UTC

    Alternately use the join function such as

    print $fh join(":", @array);
    or print a delimiter after each element (even after the last) of the array with a for loop like
    print $fh $_, "\n" for @array;
      or print a delimiter after each element (even after the last) of the array with a for loop like

      You can still use the join idiom rather than choosing a loop.

      print $fh join qq{\n}, @array, q{};

      I hope this is of interest.

      Cheers,

      JohnGG

Re: Printing Array to a file
by paragkalra (Scribe) on Jan 27, 2010 at 08:16 UTC

    Thanks to all.