Set - 2

Question 6 :

Why does Perl not have overloaded functions? 

Answer :

Because you can inspect the argument count, return context, and object types all by yourself.
In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they're references and simple pattern matching like /^\d+$/ otherwise. In languages like C++ where you can't do this, you simply must resort to overloading of functions.

Question 7 :

What does read() return at end of file? 

Answer :

A defined (but false) 0 value is the proper indication of the end of file for read() and sysread().

Question 8 :

What does `new $cur->{LINK}' do? (Assume the current package has no new() function of its own.)

Answer :


The indirect object syntax only has a single token lookahead. That means if new() is a method, it only grabs the very next token, not the entire following expression.
This is why `new $obj[23] arg' does't work, as well as why `print $fh[23] "stuff\n"' does't work. Mixing notations between the OO and IO notations is perilous. If you always use arrow syntax for method calls, and nothing else, you'll not be surprised.

Question 9 :

How do I sort a hash by the hash value? 

Answer :

Here's a program that prints the contents of the grades hash, sorted numerically by the hash value:

#!/usr/bin/perl -w
# Help sort a hash by the hash 'value', not the 'key'. to highest).
sub hashValueAscendingNum {
	$grades{$a} <=> $grades{$b};

# Help sort a hash by the hash 'value', not the 'key'. 
# Values are returned in descending numeric order 
# (highest to lowest).
sub hashValueDescendingNum {
	$grades{$b} <=> $grades{$a};

%grades = (
	student1 => 90,
	student2 => 75,
	student3 => 96,
	student4 => 55,
	student5 => 76,

foreach $key (sort hashValueAscendingNum (keys(%grades))) {
	print "\t\t$grades{$key} \t\t $key\n";

foreach $key (sort hashValueDescendingNum (keys(%grades))) {
	print "\t\t$grades{$key} \t\t $key\n";


Question 10 :

How to read file into hash array ?

Answer :

open(IN, "<name_file")
or die "Couldn't open file for processing: $!";
while (<IN>) {
	$hash_table{$_} = 0;
close IN;
print "$_ = $hash_table{$_}\n" foreach keys %hash_table;