If Net::Ping gets failure and has the special statement for the failure, how can return this statement to the caller?
Thank you. On Fri, Nov 1, 2019 at 5:30 AM Andy Bach <afb...@gmail.com> wrote: > > How do I let the caller know what happens when the method fails to run? > > As noted, die() ends the program at that point, sending the text to stderr > and setting an exit code to the shell. If you want your subs are to > communicate with their calling code, you can use the return values to show > success or failure: > sub mytest { > > my $host = shift; > my $p = Net::Ping->new(); > unless ($p->ping($host)) { > $p->close(); > return 0; > } > return 1; > } > > my $host = 'www.google.com'; > if ( not A::mytest($host) ) { > print "failed to ping: $host\n"; > } > else { > print "$host is alive\n"; > } > > The choice of returning one or zero is up to you (or anything else - a > range of values for different failures), just needs to be agreed on ahead > of time. You can do something like try/catch blocks around code that dies > by using "eval", something like: > package main; > > eval { > A::mytest('www.google.com'); > }; > if ( $@ ) { > print "A::mytest died, saying $@\n"; > } > > The Perl var "$@" gets what ever the called code might have sent to > stderr, e.g.: > $ test_net_ping.pl > A::mytest died, saying can't ping www.google.com at /usr/local/bin/ > test_net_ping.pl line 14. > > Just to note, as a package test, normally, your package A and B would be > separate scripts (say Apingtest.pm and Bpingtest.pm, in the @INC path) > and the main code would just have > #!/usr/bin/perl > use Apingtest; > use Bpingtest; > use strict; > use warnings; > ... > > On Thu, Oct 31, 2019 at 4:42 AM Maggie Q Roth <rot...@gmail.com> wrote: > >> Hello >> >> Sorry I am new to perl, I was reading the charter about package. >> >> I tried to write the code below: >> >> use strict; >> use Net::Ping; >> >> package A; >> >> sub mytest { >> >> my $host = shift; >> my $p = Net::Ping->new(); >> unless ($p->ping($host)) { >> $p->close(); >> die "can't ping $host"; >> } >> } >> >> 1; >> >> package B; >> >> sub mytest { >> >> my $host = shift; >> my $p = Net::Ping->new(); >> unless ($p->ping($host)) { >> $p->close(); >> return 0; >> } >> } >> >> 1; >> >> package main; >> >> A::mytest('www.google.com'); >> >> print B::mytest('www.google.com'); >> >> >> >> When I run it, always get: >> $ perl test.pl >> can't ping www.google.com at test.pl line 12. >> >> >> Shouldn't I return die() in package's method? >> How do I let the caller know what happens when the method fails to run? >> >> Thanks in advance. >> >> Yours >> Maggie >> > > > -- > > a > > Andy Bach, > afb...@gmail.com > 608 658-1890 cell > 608 261-5738 wk >