st_possenti has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I need to end the "do" statement with user intervention. My idea is to do this with "until" after the }} but I am unsure of how to get the until in there and accept CRTL-C as the exit. If there is a better way, let me know. Thank you in advance for your assistance.
use strict; my $line; chomp($line = <stdin>); if ($line eq "\n") { print "There was no port number!\n"; } else { do{{ $line; system ("netstat -an | grep $line \n"); system ("sleep 10"); redo; }} }

Replies are listed 'Best First'.
Re: How to end "do" with Ctrl-C
by pfaut (Priest) on Dec 02, 2008 at 22:33 UTC

    You need to trap the INT signal.

    our $stopit = 0; $SIG{INT} = sub { $stopit++; }; while (!$stopit) { system("netstat -an | grep $line"); sleep 10; }
    90% of every Perl application is already written.
    dragonchild
      Yeah, what pfaut said. As an additional note, your chomp removes the end line, so your test would always pass. If you really want to catch bad input, you could try:
      use strict; my $port = shift; our $stopit = 0; $SIG{INT} = sub { $stopit++; }; if (!$port or $port =~ /\D/) { print "usage: program port_num\n"; } else { while (!$stopit) { print system("netstat -an | grep $port"), "\n"; sleep 10; } }

      or whatever variant will get you what you want.

        print system("netstat -an | grep $port"), "\n";

        That should be

        system("netstat -an | grep $port");

        or

        print qx{netstat -an | grep $port};

        or

        print grep /$port/, qx{netstat -an};
        Thank you, works great!