03/03/2003: Sorting Arrays With Numbers Using Perl
Sorting Arrays With Numbers Using Perl
If you are looking to use the sort method to sort an array which contains numbers, the regular
sort @array
technique won't do you much good.
To sort an array, do the following:
# from least to greatest foreach$number(sort { $a <=> $b } @numbers) { print $number\n"; } # from greatest to least: foreach$number(sort { $b <=> $a } @numbers) { print $number\n"; }
03/03/2003: Reading a whole file into a scalar Using Perl
Reading a whole file into a scalar Using Perl
Quite often, it is very useful to read the contents of a file into a scalar variable. The following example shows how
this can be done. $fileName
is the name of the input file. $buffer
is a scalar where the
file contents is stored. The $/
variable contains the end-of-record delimitor. By undefining the
variable, Perl will be forced to read the entire file in one shot.
Usage:
$buffer = readFileContents($fileName)
Code:
sub readFileContents { my($fileName) = shift; my($buffer); local($/) = undef; open(FILE, $fileName) or die "couldn't open $filename for reading: $!\n"; $buffer = <FILE>; close(FILE); return($buffer); }