Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between $, @, % in Perl variable declaration? [duplicate]

Example:

my $some_variable; my @some_variable; my %some_variable; 

I know, @ seems to be for array, $ for primitive, is it totally right? What is % for?

like image 566
nicola Avatar asked Apr 05 '11 14:04

nicola


People also ask

What are the different variables in Perl?

Perl has three main variable types: scalars, arrays, and hashes.

How do we declare variables in Perl?

Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

What is the difference between my and our in Perl?

my is used for local variables, whereas our is used for global variables.


1 Answers

One of the nice things about Perl is that it comes with a built in manual. Type in the following command:

perldoc perlintro 

and take a look at the section Perl variable types. You can also see this on line with the perldoc.perl.org section on Perl variables.

A quick overview:

  • $foo is a scalar variable. It can hold a single value which can be a string, numeric, etc.
  • @foo is an array. Arrays can hold multiple values. You can access these values using an index. For example $foo[0] is the first element of the array and $foo[1] is the second element of the array, etc. (Arrays usually start with zero).
  • %foo is a hash, this is like an array because it can hold more than one value, but hashes are keyed arrays. For example, I have a password hash called %password. This is keyed by the user name and the values are the user's password. For example:

    $password{Fred} = "swordfish"; $password{Betty} = "secret";

    $user = "Fred"; print "The Password for user $user is $password{$user}\n"; #Prints out Swordfish $user = "Betty"; print "The Password for user $user is $password{$user}\n"; #Prints out secret

Note that when you refer to a single value in a hash or array, you use the dollar sign. It's a little confusing for beginners.

I would recommend that you get the Llama Book. The Llama Book is Learning Perl and is an excellent introduction to the language.

like image 97
David W. Avatar answered Oct 08 '22 20:10

David W.