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

use strict; use warnings; my @input = "1,2,3,4,5"; my $string = join ":" , @input; print "$string\n"; #output is "1,2,3,4,5" my $string2 = join ":" , 1,2,3,4,5; print "$string2"; #output is "1:2:3:4:5"

Hi monks , when I am printing $string , the output is same as printing the array @input , join is not working as expected when I am providing it an array as argument , but when I am printing $string2 the output is as expected from join function , please let me know where I am wrong.

Replies are listed 'Best First'.
Re: Doubt in usage of join function
by Athanasius (Archbishop) on Jan 07, 2019 at 07:17 UTC

    Hello Perl_Programmer1992,

    Your problem is not with the join function, but with the array assignment. The statement my @input = "1,2,3,4,5"; is not doing what you think it is. It is in fact assigning a single element to the @input array, namely the string "1,2,3,4,5".

    If you want instead to assign 5 separate elements to the array, you have two options:

    1. my @input = (1, 2, 3, 4, 5); or, even better, my @input = (1 .. 5);
    2. my @input = split /,/, "1,2,3,4,5";

    Note: a module such as Data::Dumper or Data::Dump is useful to show you the actual contents of an array (or hash), so you can easily check that its contents are what you expect them to be.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thanks @Athanasius , that was really a silly mistake from my side.

Re: Doubt in usage of join function
by davido (Cardinal) on Jan 07, 2019 at 15:52 UTC

    Consider reading perlintro, perlop, and perldata for a better understanding of creating lists, populating arrays, and using quote-like constructs. If ":", "$string\n", and "$string2\n" create strings, then "1,2,3,4,5" must also do so. And therefore if double quotes are used for creating strings, the double-quote operator must NOT be for creating lists. You instead wanted:

    my @input = (1, 2, 3, 4, 5);

    Dave