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

Hi, im trying to access the elements of a dynamic array at one shot and print them as part of a statement.
The array for instance is :

@student_list = (tom,harry,jane,amelia);

This array is populated by reading a config file and can change during consecutive runs depending on the config file input.

I need to print a comma-separated list of the students once in a single print statement which rules out the "foreach" loop i could have used.

The output should be read as :

"The list of students is tom,harry,jane,amelia "
any suggestions ?

Thanks in advance!

Replies are listed 'Best First'.
Re: Access dynamic array elements
by Corion (Patriarch) on Jun 16, 2009 at 07:24 UTC

    Why does this rule out the "foreach" loop? Do you really need a single print statement? If you really need a single print statement (because it's a homework requirement, maybe), consider looking at the join function.

      Yes, the print statement is a stringent requirement . thanks for the join suggestion , i hope it works out for me .
Re: Access dynamic array elements
by cdarke (Prior) on Jun 16, 2009 at 08:24 UTC
    You declaration of the list is missing quotes around the names (use warnings;). In addition to join, TMTOWTDI:
    use strict; use warnings; my @student_list = qw(tom harry jane amelia); { local $" = ','; print "@student_list\n"; }
Re: Access dynamic array elements
by 13warrior (Acolyte) on Jun 16, 2009 at 08:59 UTC

    Assuming that the array is always populated with the names we can print the names in a comma seperated way by using the join function.

    Sample Code :

    #!/usr/bin/perl use strict; use warnings; my @names = qw (a b d f g ); # This is filled dynamically print join(',',@names);


    Output :

    ->perl a.pl a,b,d,f,g~ >

Re: Access dynamic array elements
by Anonymous Monk on Jun 16, 2009 at 07:32 UTC