Pass hash to subroutine comes to error in perl

和自甴很熟 提交于 2019-12-02 03:17:58

The assignment is in the scalar context in your sub stop on the line

my $servs = @_;

so $servs receives the number of elements of @_, that is 1 in your code. Then the attempt to dereference that 1 with %{$servs} draws the error.

Change it to my ($servs) = @_; where the () results in the list context for =

A few comments.

  • The hash with servers is likely to be used mostly via its reference. Then why not use a hashref, my $serv = { ... }

  • There is never a reason to quote a scalar, like "$option"; just switch($option)

  • The & in front of a sub is quite special; you mostly likely need main() instead of &main

  • Second code sample has stop("@s");, whereby @s is interpolated inside "". So the sub receives a single string: array elements with spaces between them. You need stop(@s)

You seem to be using Switch module. It is a rather non-trivial source filter; surely there are other ways to do what you need. The feature switch is experimental, too. See Switch Statements in perlsyn


  The my @args = @_; serves the same purpose of course. Then process @args suitably.

A commonly seen way to retrieve the first argument is also

sub fun {
    my $first_arg = shift;  # same as: shift @_;
    ...
}

The shift removes an element from the front of its argument (array), and returns it; by default it acts on @_ which you thus don't have to write.

This is often seen in object-oriented code, to get the object off of @_ so that @_ can then be worked with more easily. But it is also often used when @_ has a single argument, for convenience.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!