An Example: Converting Fahrenheit to Celsius

With numbers, strings, and scalar variables under your belt, you can now start to write simple Perl scripts. Here's a script that prompts you for a Fahrenheit number and then converts it to Celsius. Here's what it looks like when it's run:

% temperature.pl
Enter a temperature in Fahrenheit: 212
212 degrees Fahrenheit is equivalent to 100 degrees Celsius
%

Listing 2.1 shows the Perl code for this script:

Listing 2.1. The temperature.pl Script
 1: #!/usr/local/bin/perl -w 2: 3: $fahr = 0; 4: $cel = 0; 5: 6: print 'Enter a temperature in Fahrenheit: '; 7: chomp ($fahr = <STDIN>); 8: $cel = ($fahr - 32) * 5 / 9; 9: print "$fahr degrees Fahrenheit is equivalent to "; 10: printf("%.0f degrees Celsius\n", ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.