Perl Programming Page 4 - Scalars: Building a Currency Converter |
<STDIN>reads up to and including the newline character. Sometimes we don’t want to include the newline in the text we have read, so we canchomp()the newline off the string. Thechomp()function removes the last character of a string if and only if it is the newline character. For instance: $string = "testing 1, 2, 3\n"; Since<STDIN>reads up to and including the newline character, this code reads and then removes the newline: my $input = <STDIN>; Those two statements can be combined into one: chomp(my $input = <STDIN>); A related function ischop(). It removes the last character of a string, regardless of what character it is. Here is an example: $string = "testing, 1, 2, 3"; Two Miscellaneous Functions Before we end our discussion of scalars, we should discuss two functions that are often used to terminate Perl programs: exit() and die(). The exit() Function The exit() function exits the program. If an argument is provided, it returns that value back to the calling program (or shell). If no argument is provided, it returns back the value 0. In the shell, the value 0 means that the program terminated normally, so we can report that all is well with exit(0); or exit; If the program exits abnormally due to some error condition, simply return back a nonzero value to tell the calling program that all is not well: exit(1); Here is an example of using theexit()function: #!/usr/bin/perl -w use strict; print "enter value to return back to the calling program: "; exit($value); In Unix, we can echo out the value$?to see the return value of the most recent command: $ perl exit.pl
blog comments powered by Disqus |
|
|
|
|
|
|
|