
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Private Variables in a Subroutine in Perl
By default, all variables in Perl are global variables, which means they can be accessed from anywhere in the program. But you can create private variables called lexical variables at any time with the my operator.
The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed. This region is called its scope. Lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements.
Following is an example showing you how to define a single or multiple private variables using my operator −
sub somefunc { my $variable; # $variable is invisible outside somefunc() my ($another, @an_array, %a_hash); # declaring many variables at once }
Example
Let's check the following example to distinguish between global and private variables −
#!/usr/bin/perl # Global variable $string = "Hello, World!"; # Function definition sub PrintHello { # Private variable for PrintHello function my $string; $string = "Hello, Perl!"; print "Inside the function $string\n"; } # Function call PrintHello(); print "Outside the function $string\n";
Output
When the above program is executed, it produces the following result −
Inside the function Hello, Perl! Outside the function Hello, World!