Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

the basic datatypes, three

by root (Monk)
on Oct 29, 1999 at 01:53 UTC ( [id://861]=perltutorial: print w/replies, xml ) Need Help??

Perl has three basic datatypes: scalars, arrays, and hashes.


Scalars are the most basic type of data in Perl they can represent a number(int, float, whatever) or a string of text(we won't tell you about scalars as references just yet). Here are some examples of scalar assignments:
$a=5; $b="five"; $c=5.0

One important thing to take note of is that since scalars can be either numbers or strings you need to test for equality in different ways. For numbers use == and != to test for equality and nonequality. For strings you use eq and ne to test for the same things. Here's an example: (Note scalar variables begin with an $)
$a="5.0"; # set up our variables $b="5"; # # to the end of a line is a comment in perl print "Are these variables equal as numbers? ",$a==$b,"\n"; print "Are the variables equal as strings? ",$a eq $b,"\n"; print "These variables are equal as strings\n" if($a eq $b); print "These variables are equal numerically\n" if($a==$b);

If you ran this you would see a 1 is placed in the place of $a==$b. When we compare them with a numerical comparison they are processed as numbers and therefore 5.0 and 5 are equal and it returns a 1 which means true in Perl. $a eq $b is replaced with nothing in the print statement because as strings the two variables are not equivalent. This is equivalent to false in Perl along with 0 and a few other things. For information about these type of things check What is true and false in Perl?

For more information on each of these types of scalars check:
Integer Literals in Perl
Float Literals in Perl
Strings in Perl

Functions for SCALARs or strings
chomp, chop, chr, crypt, hex, index, lc, lcfirst, length, oct, ord, pack, q/STRING/, qq/STRING/, reverse, rindex, sprintf, substr, tr///, uc, ucfirst, y///


Arrays are basically a collection of scalars stored next to each other and accessed by indices from zero to the number of elements minus one. Here are examples of some arrays in action. Note: when we're referring to an entire array we use the @ at the beginning of its name. If we're referring to only one of its elements(which is a scalar) we use a $.
@a=(1,2,3); @simpsonsfamily=("homer","marge","lisa","maggie","bart");

Arrays can store either strings or numbers or both. Now lets see how we can get at an individual element of an array.
$a[0]; #This returns the first element in @a which is 1
$simpsonsfamily[4]; #This returns the fifth element which is bart
$a[3]=4; #This sets the 4th element in @a to 4.

One nice thing about arrays in Perl is that you don't have to set the size of them when you start so they will grow for you when you need them to. To find the size of an array you can you can do scalar(@a) which would return 3 originally and 4 after $a[4] was set to 4; You can get at the highest index by using the variable $# with the arrayname attached to the end. For example $#simpsonsfamily would be equal to 4.

Some other functions I will quickly mention are push and reverse. push is followed by the array you want to add to, and then a value or list of values that you want added to the end. It would look something like:
push @array, $value; #puts $value onto the end of @array.

The reverse function simply takes a list or array and reverses it. For example, to reverse the order of an array permanently you would just type something like:
@array=reverse @array;

Functions for real @ARRAYs
pop, push, shift, splice, unshift

Functions for list data
grep, join, map, qw/STRING/, reverse, sort, unpack


Hashes are collections of scalars like arrays only they have indices or keys which are strings instead of integers. Hash variables are named with a % followed by at least one letter and then maybe a mix of some more numbers, letters, and underscores. Key and value are two important hash terms. The key is what you use to look up a value. The key is like the index in an array and the value is like the data stored there. Hashes can also be thought of as an array filled with key value pairs as you will soon see. Now we'll show you how you can initialize and access elements of an array.
@array=("key1","value1","key2","value2"); #an array filled with key +value pairs %hash1=("key1"=>"value1","key2"=>"value2"); #one way to initialize a h +ash (key=>value,key2=>value2,..) %hash2=@array; #making %hash2 out of a co +llection of key value pairs in an array $hash3{"key1"}="value1"; #creates key of "key1" and + value of "value1" $hash3{"key2"}="value2";

Now %hash1, %hash2, %hash3 all contain the very same keys and values.

Functions for real %HASHes
delete, each, exists, keys, values

Some other things you might want to check out are:
Control statements and looping
Some things that will make your life easier as a Perl coder

Replies are listed 'Best First'.
Re: the basic datatypes, three
by systems (Pilgrim) on Jul 20, 2005 at 07:50 UTC
    To find the size of an array you can you can do scalar(@a) which would return 3 originally and 4 after $a[4] was set to 4;
    I think you meant $a[3] and not $a[4] :)
    I would also like to point at this node scalar vs list context, I think most Perl newcomers need to be introduces as soon as possible to those context issues,e.g.

    What would happen if you assign a list value to a scalar variable?
    And for this particular question the answer would be, the scalar get the size value of the list.
    This is how Perl works, it's a ... rule.

    I am commenting on this mainly to point out that it's not obvious why would scalar (@list) return the list size, one would expect a function like size @list. So it would be reasonable to justify and explain those issues sooner rather than later.
    Most people like to learn why (the justification) things works in the way they do. Not just how (the rules).
      Why do we need to key scalar(@list) when only @list would also work?
      for e.g.
      use strict; my @abc= ('a','b','c','d'); my $x= @abc; my $y = scalar(@abc); print $x."#".$y;
      Here $x & $y both return 4.
        The "scalar" op is needed only to provide scalar context in an otherwise list context space. For example:
        my @lengths = scalar @x, scalar @y, scalar @z; # but... my $length_x = @x; my $length_y = @y; my $length_z = @z;
        The scalar is needed in the first example because the array names are in a list context otherwise.

        -- Randal L. Schwartz, Perl hacker
        Be sure to read my standard disclaimer if this is a reply.

      A reply falls below the community's threshold of quality. You may see it by logging in.

      What would happen if you assign a list value to a scalar variable?
      And for this particular question the answer would be, the scalar get the size value of the list.

      In your post, you keep mixing up list and array behaviour/context - or maybe you just misnamed "array" as "list".

      see davorgs post further below to clarify the difference.

      Cheers, Sören

        is there any possible way to find, what type is a variable of these three types.
Re: the basic datatypes, three
by barun (Novice) on Mar 01, 2005 at 09:56 UTC
    print %hash;

    Can anyone tell me why my order of output is like this ?
      Can anyone tell me why my order of output is like this ? Unlikely.

      For all practical purposes you cannot rely on the hash elements to be stored in any particular order. It depends on how many elements the hash has, on the value of the keys, and in recent Perl versions can be additionally randomized to prevent certain types of attacks.

      The order of the elements as returned by the keys, each and values functions is not the order of insertion or follows the alphabet. The order produced by these three functions is however internally consistent (meaning you can iterate over keys and values separately and they will match).

      You can sort the keys (for example) alphabetically if you need to do this, but you cannot recover the order of insertion.

      This may seem inconvenient, but it is (a fundamental) part of how a hash works. It is not made to retrieve elements in a certain order, but it is very fast at single-element lookups. Testing if an element exists is for example much more efficient in a hash than in an array.

Re: the basic datatypes, three
by Anonymous Monk on Mar 19, 2009 at 06:05 UTC
    I think "To find the size of an array you can you can do scalar(@a) which would return 3 originally and 4 after $a[4] was set to 4;" is wrong. If you set $a[4], scalar(@a) should return 5. I think you meant $a[3]. --skr
Re: the basic datatypes, three
by pradsag (Initiate) on Aug 29, 2012 at 11:23 UTC
    How to print the hash values....????

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perltutorial [id://861]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-21 15:13 GMT
Find Nodes?
    Voting Booth?

    No recent polls found