Greetings, Monks.
After witnessing the power of array and hash slices in responses to a previous question I had posed, I became determined that my next programming task would involve both understanding and utilizing them. What I needed was a simple challenge that would enable me to familiarize myself with them. I decided that coding a simple searching algorithm using array slices would suffice. With that goal in mind, I chose to implement a binary search algorithm, as its specification seemed the easiest to code. Here is my first novice attempt:
#!/usr/bin/perl -w
use strict;
my @list = 1..10;
print binary_search(\@list, 3);
sub binary_search {
my ($aref, $find) = @_;
my $mid;
$mid = int $#$aref / 2;
return 0 if $find == $aref->[$mid];
return 1 if !$#$aref;
if ($find > $aref->[$mid]) {
@$aref = @$aref[++$mid..$#$aref];
binary_search($aref, $find);
}
else {
@$aref = @$aref[0..--$mid];
binary_search($aref, $find);
}
}
This works as it should, though I'm positive the verbosity of the code can be greatly decreased. My question is this: why is it that when I alter this line,
@$aref = @$aref[++$mid..$#$aref];
to this:
@$aref = @$aref[++$mid..-1];
The script displays this error message:
Use of uninitialized value in numeric qt (>) at BinarySort.pl line 21? I proceeded to run the script through the perl debugger and noticed that the array slice
@$aref[++$mid..-1] returns nothing. Why is that? I was under the impression that
-1 is the same as
$#$aref in this context. Any help is appreciated.
Matt
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.