Friday, February 4, 2011

PERL : Variables

Scalar, Arrays, Hash
Scalar - has one value
Array - list of scalars
Hash - key value pares
pico scalar.pl
#!/usr/bin/perl -w
use strict; # checks the code for declarations for many other things
#Global & Lexical Variables
my $firstname = "Mark";
my $age = 43;
my $_23asd = "var";
our $count = 1; # Global
print $firstname $age;
print $count;
#Block Definition
{
my $firstname = "firstname"; # these variables are reset
my $age = "2";
print "$firstname is $age";#firstname is 2
print "$count\n";
}
print $firstname;#Mark
print $age;#43
#END


Variable must begin with aZ_
#!/usr/bin/perl -w
use strict;
print "Provide first name:";
my $firstname = <STDIN>;
print $fisrtname
#END


Arrays
pico array1.pl
#!/usr/bin/perl -w
$firstname = "Mark"; #scalar, array and hash can have the same name
@carsmanufacturer = ("Dacia","Mercedez","Nissan","Toyota","BMW");
print "Hello $firstnale. Chose a car manufacturer";
print $carsmanufacturer[0];
print $carsmanufacturer[1];
print $carsmanufacturer[2];
print $carsmanufacturer[3];
print $carsmanufacturer[4];
print "the number of manufacturer has $#carsmanufacturer+1\n"
print "@carsmanufacturer[0.1.2.3.4]" # prints all manufacturers
print "@carsmanufacturer[0..4]" # prints all manufacturers
#end


pico hash1.pl
#! /usr/bin/perl -w
$firstname = "Mark";
@fullname = ("Mark","George","McD");
%make_model = ("Honda","Accord","Toyota","Camry");#keys:Honda, Toyota; values:Accord and Camry
print $make_model{"Honda"};#prints the value of Honda
#END
perl -w hash1.pl -> Accord


pico hash1.pl
#! /usr/bin/perl -w
$make = "Honda";
$firstname = "Mark";
@fullname = ("Mark","George","McD");
%make_model = ("Honda","Accord","Toyota","Camry");#keys:Honda, Toyota; values:Accord and Camry
#the key value pear must be even
print "$make makes the : ";
print $make_model{"$make"};#prints teh value of Honda
#END
perl -w hash1.pl -> Honda makes Accord


#! /usr/bin/perl -w
$make = "Honda";
$firstname = "Mark";
@fullname = ("Mark","George","McD");
%make_model = ("Honda","Accord","Toyota","Camry");#keys:Honda, Toyota; values:Accord and Camry
#the key value pear must be even
print "$make makes the : ";
print $make_model{"$make"};#prints teh value of Honda


$player = "Venus";
%player_country = (
Venus => "USA",
Sharapova =>"Rusia",
);
print "$player represents: ";
print $player_country{"$player"};
#END
perl -w hash1.pl -> Venus represents: USA


@num_of_players = keys %player_country;
print "@num_of_players[0..$#num_of_players]\n"; -> returns the keys Venus Sharapova
@num_of_players = values %player_country;
print "@num_of_players[0..$#num_of_players]\n"; -> returns the values USA Russia
%player_country = (
Venus => "USA",
Sharapova =>"Rusia",
Serena => "USA"
);

No comments:

Post a Comment