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

This node falls below the community's threshold of quality. You may see it by logging in.
  • Comment on Can you explain me the output of this programme. especially in the subroutine func2
  • Download Code

Replies are listed 'Best First'.
Re: Can you explain me the output of this programme. especially in the subroutine func2
by ikegami (Patriarch) on Nov 26, 2007 at 16:03 UTC

    Bug 1: use strict; is missing. It'll show some encapsulation errors (i.e. a few missing mys).
    Bug 2: use warnings; is missing. It'll show Bug 3.
    Bug 3: func2 is declared after a call to it, so the prototype is ignored for that call.
    Bug 4: You're using prototypes. Don't.
    Bug 5: You modified $, without localizing it. (local $, = "...";)

    use strict; use warnings; sub func1 { my $nums = shift; print("func1: ", join(', ', @$nums), "\n"); func2($nums); } sub func2 { my $nums = shift; print("func2: ", join(', ', @$nums), "\n"); } my @nums = (10,400,2,7,20,40,23,100,2); print("main: ", join(', ', @nums), "\n"); func1(\@nums);
      ikegami, Thanks for the quick reply. Things to remember: 1. Function should be defined before it is called or prototypes will be ignored. 2. Function calls with &func1 will ignore the prototypes so better to pass references at first place rather than passing array and then taking references for it. Thanks a ton.
      SORRY !

      Bug 6: sanketkathalkar, you are calling func1 & func2 as  func1(@arr); and  func2(@arr); where you pass array itself, instead of array reference. So when you shift the arguments, you are getting the first element, which is being printed.
      ikegami fixed this in the code he posted.

        No, that's actually correct for a prototype of (\@). (Notice how func1(@arr); worked correctly?) The whole question was about why the prototype wasn't working for func2.

        That's one of the things the prototype does. If you specify (\@) then passing an array func1(@arr) is correct. Passing func1(\@arr) would actually fail the prototype check (as would suppling a list instead of an array). ikegami had to pass a reference because the prototype was removed.

        Update: my reply overlapped with that of ikegami