FAQ
Author: comdog
Date: Fri Jan 18 03:41:02 2008
New Revision: 10602

Modified:
perlfaq/trunk/perlfaq7.pod

Log:
* How do I create a switch or case statement?
+ Now that's it's 5.10, make given-when the first answer

* How do I create a static variable?
+ for 5.10, make state() the first answer


Modified: perlfaq/trunk/perlfaq7.pod
==============================================================================
--- perlfaq/trunk/perlfaq7.pod (original)
+++ perlfaq/trunk/perlfaq7.pod Fri Jan 18 03:41:02 2008
@@ -486,9 +486,11 @@

(contributed by brian d foy)

-Perl doesn't have "static" variables, which can only be accessed from
-the function in which they are declared. You can get the same effect
-with lexical variables, though.
+In Perl 5.10, declare the variable with C<state>. The C<state>
+declaration creates the lexical variable that persists between calls
+to the subroutine:
+
+ sub counter { state $count = 1; $counter++ }

You can fake a static variable by using a lexical variable which goes
out of scope. In this example, you define the subroutine C<counter>, and
@@ -688,8 +690,19 @@

=head2 How do I create a switch or case statement?

+In Perl 5.10, use the C<given-when> construct described in L<perlsyn>:
+
+ use 5.010;
+
+ given ( $string ) {
+ when( 'Fred' ) { say "I found Fred!" }
+ when( 'Barney' ) { say "I found Barney!" }
+ when( /Bamm-?Bamm/ ) { say "I found Bamm-Bamm!" }
+ default { say "I don't recognize the name!" }
+ };
+
If one wants to use pure Perl and to be compatible with Perl versions
-prior to 5.10, the general answer is to write a construct like this:
+prior to 5.10, the general answer is to use C<if-elsif-else>:

for ($variable_to_test) {
if (/pat1/) { } # do something

Search Discussions

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupcvs-perlfaq @
categoriesperl
postedJan 18, '08 at 11:41a
activeJan 18, '08 at 11:41a
posts1
users1
websitelearn.perl.org...

1 user in discussion

Comdog: 1 post

People

Translate

site design / logo © 2019 Grokbase