in reply to Can you explain me the output of this programme. especially in the subroutine func2

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);
  • Comment on Re: Can you explain me the output of this programme. especially in the subroutine func2
  • Select or Download Code

Replies are listed 'Best First'.
Re^2: Can you explain me the output of this programme. especially in the subroutine func2
by sanketkathalkar (Initiate) on Nov 27, 2007 at 09:11 UTC
    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.
Re^2: Can you explain me the output of this programme. especially in the subroutine func2
by atemon (Chaplain) on Nov 26, 2007 at 16:18 UTC
    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
        Update: my reply overlapped with that of ikegami

        Why the update? Why apologize for posting correct information?