arrays - Perl while loop won't exit when blank line is entered -


i trying print sum, maximum, , minimum values of list of numbers struggling working.

when press enter loop should exit program keeps running

use strict; use warnings;  @items; ( $sum, $max, $min );  while ( chomp( $num = <stdin> ) ) {     last if ( $num eq '\n' );      $max ||= $num;     $min ||= $num;     $sum += $num;      $max = $num if ( $num > $max );     $min = $num if ( $num < $min );      push( @items, $num ); }  printf( "entered numbers are: %s \n", join( ', ', @items ) ); print( "sum of numbers : ", $sum ); print "\n"; print( "minimum number : ", $min ); print "\n"; print( "maximum number : ", $max ) 

  • you can't use chomp inside while condition this

    while (chomp(my $num = <stdin>)) { ... } 

    because while loop needs terminate when <> returns undef @ end of file. must put chomp first statement of loop

  • the simplest way exit loop check whether input contains non-space characters using regular expression /\s/

  • the check

    last if ( $num eq '\n' ) 

    won't work because have used chomp remove newline input. also, if use single quotes '\n' two-character string \ followed n. need double quotes "\n" create newline

  • when scalar variable first declared has value undef, can avoid clumsy initialisation testing , updating $min , $max unless previous value defined , higher (or lower) new value

i rewrite program this.

use strict; use warnings;  @items; ($sum, $max, $min);  while (my $num = <stdin>) {   chomp $num;   last unless $num =~ /\s/;    $max = $num unless defined $max , $max >= $num;   $min = $num unless defined $min , $min <= $num;   $sum += $num;   push @items, $num; }  print 'entered numbers are: ', join(', ', @items), "\n"; print "sum of numbers is: $sum\n"; print "minimum number is: $min\n"; print "maximum number is: $max\n"; 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -