LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to break if loop in Perl? (https://www.linuxquestions.org/questions/programming-9/how-to-break-if-loop-in-perl-347774/)

Barca 07-28-2005 03:15 PM

How to break if loop in Perl?
 
How to break "if" checking in Perl? Let's see:

if ($cap)
{
Net::Pcap::close ($cap);
>>> HERE <<<
print "\nExit\n";
}

I'd like to add another "if" block in this. I'd like to exit from "if" checking in marked place if variable $test would be equal to 1. So, if $test =1, $cap will be closed but text "Exit" won't be displayed.
How to do that? "last" doesn't seem to work, because it's designed to use in "while" loops etc., not in "If" statement. Thanks for your help :)

Matir 07-28-2005 03:21 PM

Yeah, if is not a loop, but a language construct. That aside, the only solution I'm aware of is the ultra-ugly "goto". :)

Barca 07-28-2005 03:42 PM

Thx it helped ;) I doesn't think that using goto is bad. I'd say that using it too many times isn't good, but it's not "ugly" as many people says. It's a command like any other, created to be used when necessary - like in this example :)

Matir 07-28-2005 03:48 PM

Yeah, well, there essays out there on using goto (and when to or not to).

Which makes me wonder how an optimizing compiler would handle this: (granted, this is C code)
Code:

void foo(){
    goto subarea;
    if( 0 ) /* False constant condition */
    {
        subarea:
        printf("Hit subarea.\n");
    }
}


luxitan 07-28-2005 04:00 PM

Maybe I don't understand the problem but why don't you use another if:

Code:



if ($cap)
{
  Net::Pcap::close ($cap);
  if (!$test)
  {
    print "\nExit\n";
  }
}


Matir 07-28-2005 04:18 PM

No, he seems to be desiring to break out of multiple areas, as in this code:
Code:

if($cap)
{
    Net::Pcap::close($cap);
    if(!$test){
        goto outside;
    }
    # more code
}
outside:
#even more code


f76 07-29-2005 08:48 AM

how about else?

nkthrasher 08-01-2005 03:28 PM

Too easy.

Code:

for(;;){
  if ($cap){
    Net::Pcap::close ($cap);
    if(wewanttobreakhere){
      last;
    }
    #insert other code here
    if(wewanttobreakhere){
      last;
    }
    print "\nExit\n";
  }
  last;
}

Cant break from the if since its not a loop, but you can put the if into a useless loop, and break from the useless loop.

Matir 08-01-2005 03:35 PM

How about placing that within [ code] brackets? ;)

jaylink1971 08-03-2011 01:15 PM

We're all so stupid. Just do this, as suggested by "John" in another forum:

just put a loop inside the if block:

Code:

if ( $expression ) { {
 last if $oops;
 } }



All times are GMT -5. The time now is 01:24 AM.