I am relatively new to Perl and I do not want to use the List::Util max
function to find the maximum value of a given array.
When I test the code below, it just returns the first value of the array, not the maximum.
sub max
{
my @array = shift;
my $cur = $array[0];
foreach $i (@array)
{
if($i > $cur)
{
$cur = $i;
}
else
{
$cur = $cur;
}
}
return $cur;
}
To refer to a single element of an array, the variable name must start with a $ followed by the index of the element in square brackets ( [] ). The index of the first array element is 0.
unshift() function in Perl places the given list of elements at the beginning of an array. Thereby shifting all the values in the array by right. Multiple values can be unshift using this operation. This function returns the number of new elements in an array.
Perl provides a shorter syntax for accessing the last element of an array: negative indexing. Negative indices track the array from the end, so -1 refers to the last element, -2 the second to last element and so on.
Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets.
Replace
my @array = shift;
with
my @array = @_;
@_
is the array containing all function arguments. shift
only grabs the first function argument and removes it from @_. Change that code and it should work correctly!
Why don't you want to use something that works?
One of the ways to solve problems like this is to debug your data structures. At each step you print the data you have to see if what you expect is actually in there. That can be as simple as:
print "array is [@array]\n";
Or for complex data structures:
use Data::Dumper;
print Dumper( \@array );
In this case, you would have seen that @array
has only one element, so there it must be the maximum.
If you want to see how list assignment and subroutine arguments work, check out Learning Perl.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With