How to use ARRAY in PERL ?

How to use ARRAY  in PERL ?
Example 1

#!/usr/bin/perl
@array = (1..5);
print @array;     print “\n”;
print $array[0];  print “\n”;
print $array[1];  print “\n”;
print $array[2];  print “\n”;
print $array[3];  print “\n”;
print $array[4];  print “\n”;

Example2

#!/usr/bin/perl
@emptyArray = ();
@numberArray = (12, 014, 0x0c, 34.34, 23.3E-3);
@stringArray = (“This”, “is”, ‘an’, “array”, ‘of’, “strings”);
@mixedArray = (“This”, 30, “is”, ‘a’, “mixed array”, ‘of’, 0x08, “items”);

print “Here is an empty array:” . @emptyArray . “<- Nothing there!\n”;
print @numberArray; print “\n”;
print @stringArray; print “\n”;
print @mixedArray; print “\n”;

@smallArrayOne = (5..10);
@smallArrayTwo = (1..5);
@largeArray = (@smallArrayOne, @smallArrayTwo);

print @largeArray;

Example 3

#!/usr/bin/perl
# Create a four-element array and assign it to @array.
# Use an array slice to assign the first and third elements to $first and $third.
# Use an array slice to assign the second half of the array to @half.
# Print @array, $first, $third, and @half to verify their values.
# Tranpose the first and last elements in @array.
# Print @array to verify that the elements have been switched.

@array = (“One”, “Two”, “Three”, “Four”);
($first, $third) = @array[0, 2];
@half = @array[2, 3];

print(“\@array=@array\n”);
print(“\$first=$first \$third=$third\n”);
print(“\@half=@half\n”);

@array[0, 3] = @array[3, 0];
print(“\@array=@array\n”);

Example 4 pop push shift unshift

#!/usr/bin/perl
@array = (1,2,3,4,5);
print @array;
print”\n”;

pop(@array);
print @array;
print”\n”;

push(@array,6);
print @array;
print”\n”;

shift(@array);
print @array;
print”\n”;

unshift(@array,7);
print @array;
print”\n”;

Example 5
#!/usr/bin/perl
@item = (‘carrot’,’beans’,’rice’,’mize’);
foreach $it(@item){
print $it.”\n”;
}
#$_default variable
foreach (@item){
print reverse($_).”\n”;
}

Example 6

#!/usr/bin/perl
$info = “Caine:Michael:Actor:14, Leafy Drive”;
@personal = split(/:/, $info);
foreach(@personal){
print $_.”\n”;
}

0Shares

Leave a Reply

Your email address will not be published. Required fields are marked *