http://www.perlmonks.org?node_id=1218800

dideod.yang has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks. I want to achieve using personal function with many arrays. Below script, I show you sample. According script, only print A... I want to print all of values(A B C) in @x. How can I achieve my personal function.
my (@x,@y); @x =( "A" "B" "C"); @y =( "C" "D" "F"); &test(@x,@y): sub &test{ @test = @_[0]; print "@test\n"; }

Replies are listed 'Best First'.
Re: About personal function
by kevbot (Vicar) on Jul 19, 2018 at 05:16 UTC
    Hello dideod.yang,

    Your script is not valid perl syntax. I recommend that you take a closer look at some documentation in order to become more familiar with perl syntax and debugging.

    Here is a modified version of your script that will print the first element of @x, which is 'A'. It will also print all the elements of @x (joined by commas).

    #!/usr/bin/env perl use strict; use warnings; my @x = ( 'A', 'B', 'C'); my @y = ( 'C', 'D', 'F'); test(\@x,\@y); sub test{ my ($x, $y) = @_; print "First element of x is: ", $x->[0], "\n"; print "All elements of x are: ", join(', ', @{$x}), "\n"; }

Re: About personal function
by NetWallah (Canon) on Jul 19, 2018 at 05:20 UTC
    Also see Pass-by-Reference to understand why kevbot passed reference to arrays.

                    Memory fault   --   brain fried

Re: About personal function
by atcroft (Abbot) on Jul 19, 2018 at 05:20 UTC

    (First of all, the code you gave throws the error message "Illegal declaration of anonymous subroutine", which would be fixed by removing the & from the sub declaration. Also, if "@test" is changed to "my @test" in line 8, the code will work under "use strict" and "use warnings", both of which may be helpful to you later on.)

    When your &test routine is entered, @_ will contain the contents of both @x and @y, flattened into a single array (i.e., @_ contains ( "A", "B", "C", "C", "D", "F", ) ). You, however, are currently assigning to @temp the value of @_[0] (better written as $_[0]), which is the first entry of @_ (or "A"). There are two ways I can see going. The simplest is to change that line to something like @test = @_;, wherein you will get the string "A B C C D F".

    If you want to get them as separate arrays, then you can pass them by reference, and then loop through the elements in @test in the loop (example derivation below; the -l switch appends an appropriate EOL for each print statement).

    Hope that helps.