Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: Wrong content of variable passed to sub

by state-o-dis-array (Hermit)
on Aug 20, 2013 at 22:55 UTC ( #1050263=note: print w/replies, xml ) Need Help??

in reply to Wrong content of variable passed to sub

Try this in your sub:
sub get_sensor_id($) { my ($sensor) = @_; print "sensor input: $sensor\n"; return 0; }
There are some other things I would do differently (like:
$value =~ s/^\s+|\s+$//g;
), but this should address your primary concern.

Replies are listed 'Best First'.
Re^2: Wrong content of variable passed to sub
by olafmar (Novice) on Aug 21, 2013 at 20:24 UTC

    I thought that @_ meant the list passed to the sub, so I used $_ when I passed a single element. My bad, I should have read perlsub better (or simply reread it).

    I used your new regexp together with the suggestions below.

      I thought that @_ meant the list passed to the sub, so I used $_ when I passed a single element.

      @_ contains the list of arguments for a sub, but you want the first argument of that array, which is $_[0]. $_ is something completely different, as you already know.

      There are two common idioms for accessing arguments:

      sub foo { my $onlyarg=shift; # @_ is the default argument for shift # more code }


      sub bar { my ($huey,$dewey,$louie)=@_; # more code }

      Of course, you can also write

      sub baz { my $onlyarg=$_[0]; # more code }


      sub moo { my $huey=shift; my $dewey=shift; my $louie=shift; # more code }

      or even

      sub ohnononononopleaseno { my $huey=$_[0]; my $dewey=$_[1]; my $louie=$_[2]; # more code }

      But that is uncommon and has some strange accent. Stick with the first two variants. Having only one argument needs no exception, you can use the list assignment even for a single argument, no need for shift:

      sub foo2 { my ($onlyarg)=@_; # more code }

      Just remember the parentheses, or else $onlyarg will contain the number of arguments, in this case 1. Not what you want.


      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1050263]
LanX 1 ..2 ..3 ..4 .. is erix missing ;-)
LanX is Discipulus reciting "Springtime for Hitler" ?
[choroba]: erix could tell you how to do it in Postgres
[chacham]: wow, mysql really is as bad as i thougt
[choroba]: completion?
[LanX]: That's what he usually does when MySQL is mentioned ;-)
[chacham]: the same thing could be achieved with a trigger
[LanX]: choroba yes
chacham shudders at the thought of using a evil

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (11)
As of 2017-03-30 15:10 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (360 votes). Check out past polls.