http://www.perlmonks.org?node_id=172268


in reply to Re: Battle script
in thread Battle script

Of course, one doesn't need those newfangled thread thingies. Here's one that can easily be backported to old versions of perl, and is using fork() and signals.

#!/usr/bin/perl -w my $hp = 100; my $pid; sub get_hit; sub get_hit { unless (-- $hp) { kill USR2 => $pid or warn "Failed to send victory: $!\n"; print "$$: Arrrgh, I am dying!\n"; exit; } print "$$: I got hit! $hp hitpoints left.\n"; $SIG {USR1} = \&get_hit; } $SIG {USR1} = \&get_hit; $SIG {USR2} = sub {print "$$: I won! I won!\n"; exit}; $pid = fork; die "Fork failed\n" unless defined $pid; $pid ||= getppid; while (1) { my $timeleft = rand 1; (undef, $timeleft) = select (undef, undef, undef, $timeleft) while $timeleft; kill USR1 => $pid; # Ignore errors. } __END__
Abigail