Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't last outside a loop block

Tags:

perl

I am trying to solve a problem

Rahul is playing a very interesting game. He has N disks ( each of equal radius). Every disk has a distinct number out of 1 to N associated with it. Disks are placed one over other in a single pile.

Rahul wants to sort this pile of disk in increasing order from top to bottom. But he has a very very special method of doing this. In a single step he can only choose one disk out of the pile and he can only put it at the top.

Rahul wants to sort his pile of disks in minimum number of possible steps. So help Rahul in doing so. So don't have to show the actual steps just answer the minimum number of possible steps to sort the pile so that that Rahul can check whether he is doing his work right or wrong.

Code i am writing is

sub get_order { 
    my (@input1)= @_; 
    my @input2 = @input1;

    my $count = 0;
    sub recursive {
        my $max = 0;
        last if ( $#input2 == -1 ) ;
        foreach ( 0 .. $#input2) {
            $max = $max > $input2[$_] ? $max : $input2[$_];
            print " maximum is $max \n";
        }
        if ( $max == $input2[$max-1] ) { 
            $abc = 0;
        } else {
            $count++;
            #push @input2, $max;
        }
        # deleting that particular array index from the array
        my %hash = map { 
            $_ => "1" 
        } @input2;
        delete $hash{$max};
        print %hash;
        print "\n";
        @input2 = keys %hash;
        print "***@input2 \n";
        &recursive();
    }
    &recursive();
    print "value is $count \n"; 
    return $count;

 }

get_order(3,1,2);

I am getting a error Can't "last" outside a loop block at test.txt line 8.

like image 798
Sumit Avatar asked Dec 06 '25 08:12

Sumit


2 Answers

Outside of for, foreach, while, until, or a naked block, you can't use last, next or redo

Instead you can return from function,

return if ( $#input2 == -1 ) ;
like image 67
mpapec Avatar answered Dec 08 '25 22:12

mpapec


Part of the code is

sub recursive {
    my $max = 0;
    last if ( $#input2 == -1 ) ;
    foreach ( 0 .. $#input2) {

in these lines last does not occur within a for loop. Hence the error message.

last is used to exit from loop. If you want to exit from a sub then use return.

like image 33
AdrianHHH Avatar answered Dec 08 '25 20:12

AdrianHHH