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

Hi Monks, I am a newbie trying to wrap my head around perl. when i was trying out a piece of code which searches a target number from the given number.I'm getting an error when i run this piece of code.

sub search { my ( $number, $target ) = @_; foreach my $i ( 0 .. $#$number ) { return $i if $i == $target; } return; } print search (100,50);

what is wrong with this code ? Thanks and happy new year 2015.

  • Comment on RE: Can't use string ("100") as an ARRAY ref while "strict refs" in use at ./divide_con_210.pl line 19.
  • Download Code

Replies are listed 'Best First'.
Re^2: Can't use string ("100") as an ARRAY ref while "strict refs" in use at ./divide_con_210.pl line 19.
by jmmitc06 (Beadle) on Jan 02, 2015 at 01:43 UTC
    Yes, you should use $number instead of $#$number. The problem here is when you use $#$number, this tells perl that you want the length of an array ref $number, but in this case that is not array ref, it's a string "100".
Re^2: Can't use string ("100") as an ARRAY ref while "strict refs" in use at ./divide_con_210.pl line 19.
by LanX (Saint) on Jan 01, 2015 at 23:45 UTC
    > $#$number

    (wtf ?)

    try $number

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

Re^2: Can't use string ("100") as an ARRAY ref while "strict refs" in use at ./divide_con_210.pl line 19.
by GrandFather (Saint) on Jan 02, 2015 at 08:27 UTC

    Where did the idea for this code come from? The coding style doesn't look like "newbie" to me, so most likely you've cargo culted some code from somewhere without really knowing what it does. If so, (actually regardless) you should take a browse through the Tutorials section here. Also Ovid's Begining Perl is also likely to be of interest and is freely available.

    Perl is the programming world's equivalent of English
      I'm using the book you've mentioned --Beginning perl by Ovid. This excerpt is from sub-routines chapter 7. I was trying out the code given in the book and got the error. Now i understand what the problem is. Thanks.
Re^2: Can't use string ("100") as an ARRAY ref while "strict refs" in use at ./divide_con_210.pl line 19.
by Anonymous Monk on Jan 02, 2015 at 02:39 UTC
    mmm, isn't it the same as
    sub search { my ($number, $target) = @_; return $target if $target <= $number; }