Do we really need "goto" here?

Emeka

On Mon, Aug 22, 2011 at 10:03 AM, Shlomi Fish <shlo...@shlomifish.org>wrote:

> Hi Alan,
>
> On Mon, 22 Aug 2011 13:10:05 +0530
> Alan Haggai Alavi <alanhag...@alanhaggai.org> wrote:
>
> > Hello Anant,
> >
> > > i want to input some numbers via <stdin> in while loop.And loop should
> be
> > > broken if any nonnumeric character is entered.So how it can be checked.
> > >
> > > ........................
> > > .........................
> > > my @ln;
> > > my $i=0;
> > > print"Give line numbers you want to put into array.\n";
> > > while(1){
> > >  $ln[$i]=<stdin>;
> > >  chomp $ln[$i];
> > >  if($ln[$i] =~ /\D/){
> > >   print"Its not numeric value.\n";
> > >   $i--;
> > >   last;
> > >  }
> > >  $i++;
> > > }
> > > .............................
> >
> > In the above program, `$i` is mostly useless. The length of the array can
> > easily be found out by using `scalar @ln`; Perl's `push` function can be
> used
> > for pushing values into the array. There is no need for an index. The
> program
> > can be rewritten as:
> >
> > use strict;
> > use warnings;
> >
> > my @numbers;
> > print "Enter numbers:\n";
> > while (1) {
> >     chomp( my $number = <STDIN> );
> >     if ( $number =~ /\D/ ) {
> >         print "$number is not a numeric value.\n";
> >         last;
> >     }
> >     else {
> >         push @numbers, $number;
> >     }
> > }
>
> It's a good idea to always use "last LABEL;" instead of "last;" (as well as
> "next LABEL;" etc. in case more loops are added in between.
>
> So the program becomes:
>
> [CODE]
> use strict;
> use warnings;
>
> my @numbers;
> print "Enter numbers:\n";
> STDIN_LOOP:
> while (1) {
>    chomp( my $number = <STDIN> );
>    if ( $number =~ /\D/ ) {
>        print "$number is not a numeric value.\n";
>         last STDIN_LOOP;
>    }
>    else {
>        push @numbers, $number;
>    }
> }
> [/CODE]
>
> See:
>
> http://perl-begin.org/tutorials/bad-elements/#flow-stmts-without-labels
>
> Regards,
>
>        Shlomi Fish
>
> --
> -----------------------------------------------------------------
> Shlomi Fish       http://www.shlomifish.org/
> What Makes Software Apps High Quality -  http://shlom.in/sw-quality
>
> Live as if you were to die tomorrow. Learn as if you were to live forever.
>    — http://en.wikiquote.org/wiki/Mohandas_Gandhi (Disputed)
>
> Please reply to list if it's a mailing list post - http://shlom.in/reply .
>
> --
> To unsubscribe, e-mail: beginners-unsubscr...@perl.org
> For additional commands, e-mail: beginners-h...@perl.org
> http://learn.perl.org/
>
>
>


-- 
*Satajanus  Nig. Ltd


*

Reply via email to