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

I call a subroutine suplying a variable and want the script to sleep for that amount of time. But it seems that the subroutine does not sleep (or at least only 1 second). Here is the script:
#!/usr/bin/perl -w use strict; while () { my $wait = 6000; my $time_now= time; &wait ($wait); print time-$time_now,"\n"; } sub wait{ my $time =@_; sleep $time; }
The Output is
1 1 1 ...
Any ideas how this poor subroutine can get some more sleep?

Replies are listed 'Best First'.
Re: Subroutine does not sleep
by hgolden (Pilgrim) on Oct 06, 2006 at 14:29 UTC
    Hey

    You're calling the array in scalar context, so it's returning the number of elements in it (which is 1). Try using shift: my $time=shift;

    Hays

Re: Subroutine does not sleep
by monkey_boy (Priest) on Oct 06, 2006 at 14:29 UTC
    change
    sub wait{ my $time =@_; sleep $time; }

    to
    sub wait{ my ($time) =@_; sleep $time; }

    As in this scalar context $time is being set to the size of @_ (i.e. 1) instead of the value.


    This is not a Signature...
Re: Subroutine does not sleep
by davorg (Chancellor) on Oct 06, 2006 at 14:31 UTC
    my $time =@_;

    You're evaluating the array, @_, in scalar context. So you get the number of elements. Try using this instead:

    my ($time) = @_;
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Subroutine does not sleep
by arkturuz (Curate) on Oct 06, 2006 at 14:34 UTC
    In wait function read the parameter like: my $time = shift or my ($time) = (@_). Also, there is a perl function wait. You should name your functions differently, to avoid clashes with builtins.
Re: Subroutine does not sleep
by kwaping (Priest) on Oct 06, 2006 at 14:54 UTC
    Also, don't forget to turn on autoflush ($| = 1; will do that). Otherwise, your perception of what the program is doing is going to be skewed by output buffering.

    Update: I re-read the thread and realized my reply doesn't address the issue. However, I feel it's still good general advice for something like this.

    ---
    It's all fine and dandy until someone has to look at the code.
      But the advice isn't that useful. He's printing to the terminal, and the terminal is in line-buffer mode. Regardless of the value of $|, as soon as a newline is printed (which he does), the output gets flushed.