PERL - Define Some Variables
A variable is defined by the ($) symbol (scalar), the (@) symbol (arrays), or the (%) symbol (hashes).Here is what each type of variable should look like inside of a script.
definevariables.pl:
#!/usr/bin/perl print "Content-type: text/html \n\n"; #HTTP HEADER $somenumber = 4; $myname = "some string"; @array = ("value00","value01","value02"); %hash = ("Quarter", 25, "Dime", 10, "Nickle", 5); ## OR ## my $somenumber = 4; my $myname = "some string"; my @array = ("value00", "value01", "value02"); my %hash = ("Quarter", 25, "Dime", 10, "Nickle", 5);
Perl - Scalar Variables
Scalar variables are simple variables containing only one element--a string, a number, or a reference. Strings may contain any symbol, letter, or number. Numbers may contain exponents, integers, or decimal values. The bottom line here with scalar variables is that they contain only one single piece of data. What you see is what you get with scalar variables.definescalars.pl:
#!/usr/bin/perl print "Content-type: text/html \n\n"; #HTTP HEADER # DEFINE SOME SCALAR VARIABLES $number = 5; $exponent = "2 ** 8"; $string = "Hello, Perl!"; $stringpart_1 = "Hello, "; $stringpart_2 = "Perl!"; $linebreak = "<br />"; #HTML LINEBREAK TAG # PRINT THEM TO THE BROWSER print $number; print $linebreak; print $exponent; print $linebreak; print $string.$linebreak; print $stringpart_1.$stringpart_2;
Display:
5
2 ** 8
Hello, Perl!
Hello, Perl!
Scalars are very straight forward. Notice that we used a period (.) between each of our variables. This is a special kind of operator that concatenates two or more variables.2 ** 8
Hello, Perl!
Hello, Perl!
Perl - Array Variables
Arrays contain a list of scalar data (single elements). A list can hold an unlimited number of elements. In Perl, arrays are defined with the at (@) symbol.definearrays.pl:
#!/usr/bin/perl print "Content-type: text/html \n\n"; #HTTP HEADER #DEFINE SOME ARRAYS @days = ("Monday", "Tuesday", "Wednesday"); @months = ("April", "May", "June"); #PRINT MY ARRAYS TO THE BROWSER print @days; print "<br />"; print @months;
Display:
MondayTuesdayWednesday
AprilMayJune
AprilMayJune
Perl - Define A Hash
Hashes are complex lists with both a key and a value part for each element of the list. We define a hash using the percent symbol (%).definehashes.pl:
print "Content-type: text/html \n\n"; #HTTP HEADER #DEFINE SOME ARRAYS %coins = ("Quarter", 25, "Dime", 10, "Nickle", 5); %ages = ("Jerry", 45, "Tom", 22, "Vickie", 38); #PRINT MY HASHES TO THE BROWSER print %coins; print "<br />"; print %ages;
Display:
Dime10Nickle5Quarter25
Jerry45Vickie38Tom22
Hashes are very complex data types, for now just understand the
syntax of how to define one. Later we will take a closer look at these
complex variables.Jerry45Vickie38Tom22
0 comments:
Post a Comment