Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

break out my foreach loop

by hmb104 (Sexton)
on Sep 02, 2012 at 06:27 UTC ( #991234=perlquestion: print w/replies, xml ) Need Help??
hmb104 has asked for the wisdom of the Perl Monks concerning the following question:

How I can break out my foreach loop?

I'm checking if IP exists on a Cisco routing table, if it does then we can get more info. I want to say if the IP doesn't exist then break the loop with error. I have the following and it works great until I enter a non-valid IP which doesn't exist on my router:

foreach $match ( @Output ) { if ( $match =~ m/^Routing entry for / ) { @Data = split( ' ', $match ); $octet = $Data[ 3 ] ; last ; } } my @routing = split( /\./, $octet );

How I can add to say if m/^Routing entry for / didn't show up in all lines then die()? I have tried many ways and it never works

Replies are listed 'Best First'.
Re: break out my foreach loop
by lidden (Curate) on Sep 02, 2012 at 06:39 UTC
    Put my $octet; # or $octet = undef before the loop and do die "Some message" unless $octet; after the loop.

      Thanks lidden, it works as intended. Is there a way to remove the error line from the die() msg?

      ERROR: IP not range: at /home/skippy/ line 177.

      Thanks for the heads up

        die "Some message\n";
Re: break out my foreach loop
by philiprbrenan (Monk) on Sep 02, 2012 at 12:10 UTC

    Or make it a sub so you can return an empty list if not found:

    use feature ":5.14"; use warnings FATAL => qw(all); use strict; use Data::Dump qw(dump pp); sub match($) { my ($Output) = @_; for my $match ( @$Output ) { if ( $match =~ m/^Routing entry for / ) { my @Data = split( ' ', $match ); my $octet = $Data[ 3 ] ; return split( /\./, $octet ) } } () } say "@{[match([split /\n/, <<'END'])]}"; a b c Routing entry for END


    1 2 3 4
Re: break out my foreach loop
by NetWallah (Canon) on Sep 03, 2012 at 00:12 UTC
    Somewhat more concise code:
    my $octetstr; ($octetstr)= m/^Routing entry for\s+([\d\.]+)/ and last for @Output; die "No Routing address found in \@Output\n" unless $octetstr;
    Update: If this is IPV4, you can extract the octets of the IP using
    my @Route; @Route= m/^Routing entry for\s+(\d+)\.(\d+)\.(\d+)\.(\d+)/ and last fo +r @Output; die "No Routing address found in \@Output\n" unless @Route;

                 I hope life isn't a big joke, because I don't get it.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://991234]
Approved by lidden
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2018-03-25 02:29 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (299 votes). Check out past polls.