Sams Teach Yourself Perl in 24 Hours (3rd Edition)

 <  Day Day Up  >  

Q&A

Q1:

Is there really any difference between using & and not using & when calling a subroutine?

A1:

None that should concern you at this point. A subtle difference does exist between &foo and foo when subroutine prototypes are used or when a subroutine is called without parentheses. These are topics well beyond the scope of this book, but for the curious , they're documented in the perlsub manual page.

Q2:

When I use my($var) in a program, Perl responds with a syntax error, next 2 tokens my( message.

A2:

You either have mistyped something or have Perl version 4 installed. Type perl -v at a command prompt. If Perl responds with version 4, you should upgrade immediately.

Q3:

How do I pass (or return) functions, filehandles, multiple arrays, or hashes to a subroutine?

A3:

For passing functions, multiple arrays, and hashes, you need to use a reference, which is covered in Hour 13. For passing filehandles to and from a subroutine, you need to use either something called a typeglob or the IO::Handle module, both of which are beyond the scope of this book.

Q4:

A function I'm using returns many values, but I'm interested in only one. How do I skip some return values?

A4:

One method is to make a literal list out of the function by wrapping the entire function call in parentheses. When it's a list, you can use ordinary list slices to get pieces of the list. The following extracts just the year (current year minus 1900) from the built-in function localtime , which actually has nine return values:

print "It is now ", 1900+ (localtime)[5];

The other method is to assign the return value from the function into a list and simply assign the unwanted values to undef or a dummy variable:

(undef, undef, undef, undef, undef, $year_offset)=localtime;

 <  Day Day Up  >  

Категории