You ask a lot of questions.
sub UNIQUE::print{print 'Hello World!'} UNIQUE->print(333); sub UNIQUE::print{ print "\nMuhahaha! @_ \n"; } UNIQUE->print(65.65.65.65); # Okay this is weird.
First of all, how does 65 become letter 'A' without using chr(65) ?
You're creating a "version string" (see version). Version strings convert the numbers to characters.
Secondly, Perl allows me to redefine my UNIQUE::print and now this second definition overwrites the first one. What happened to the first one???
Perl executes your code in two phases. First it compiles your code. This is when your second declaration of UNIQUE::print overwrites your first declaration. This phase is commonly called the "compile" phase. Then, Perl runs the code. This is when all calls go to the (second) UNIQUE::print function and produce output.
What on earth is this?
sub {5};
It's an anonymous subroutine, that is, a subroutine that you cannot call by name. You usually store it in a variable so that you can access it in other places of your program:
my $five = sub { 5 }; print $five->();
Anonymous subroutines are what makes map and grep useful. Also see Higher Order Perl for a good introduction where anonymous subroutines come in handy.
Wait. This is not supposed to work! If I declare a sub within a sub, then the inner sub should not be accessible from the outside. Is this right??? I mean what's the point of declaring a sub within a sub if it's the same as declaring it outside the sub?sub Red { sub LittleRed{'red'}; # sub within a sub LittleRed; # returns 'red' } print "\nPerl is getting confused here..." . Red; print "\n\n"; print LittleRed;
Declaring named subroutines within other named subroutines usually is an error. The visibility of subroutine names is global (except for lexical named subroutines, but these are experimental). Declaring nested named subroutines often leads to interesting problems which most often are shown by warnings as Variable %s will not stay shared.
Now, why is this not printing 10?? When the while loop ends, $i equals 10, so if I just say "$i" then it should use that as a return value for the sub. No?sub Y{ my$i=0; $i while($i++<10); } print"\nYES>".Y;
No. $i is not the expression returned from the last statement. A subroutine evaluates to the value of its last statement.
Is there a way to access previous return values? Example:sub DDD { 0; 1; 2; 3; 4; 5; } print DDD;
Yes. Use a comma instead of a semicolon (that is, return a list):
sub DDD { 0, 1, 2, 3, 4, 5, }
In reply to Re: Trying to understand Perl :-)
by Corion
in thread Trying to understand Perl :-)
by harangzsolt33
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |