Perl Programming Question:

Download Job Interview Questions and Answers PDF

How do you give functions private variables that retain their values between calls?

Perl Programming Interview Question
Perl Programming Interview Question

Answer:

Create a scope surrounding that sub that contains lexicals.
Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus:
{ my $i = 0; sub next_i { $i++ } sub last_i { --$i } }
creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.

Download Perl Programming Interview Questions And Answers PDF

Previous QuestionNext Question
How many ways can we express string in Perl?Why do you use Perl?