#!/usr/bin/perl -w use strict; my $data; my $ERROR = 0; # error(); # uncomment this to print $data before the loop while ( (defined $data++) && everything_is_okay() ) { print "looping for the $data time.\n"; if ( $data > 5 ) { $ERROR++; error(); # print $data if there's an error } } sub everything_is_okay { if ( $ERROR ) { print STDERR "ERROR LEVEL $ERROR\n"; exit $ERROR; } return 1; } sub error { print $data; }