Welcome to WebmasterWorld Guest from 54.196.208.187

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

perl how to print array

perl use foreach to print array

     
6:21 pm on Jul 18, 2015 (gmt 0)

System Operator from US 

incredibill is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Jan 25, 2005
posts:14664
votes: 99


Here's a simple way to get a Perl array displayed line by line in HTML using foreach.
@arr = ( "yellow","red","blue" );

foreach(@arr) {
print "$_<br>";
}

Now to make each element a variable as you iterate the list:
foreach my $item (@arr) {
print "item=$item<br>";
}

If you want the array sorted, easily accomplished as follows by adding the SORT keyword:
foreach my $item (sort @arr) {
print "sorted=$item<br>";
}

Hope this helps a few new to Perl.
7:51 pm on July 24, 2015 (gmt 0)

Senior Member from GB 

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month

joined:Aug 13, 2003
posts: 1053
votes: 3


I recently realised you can use the join statement too, which is useful when debugging as it is just one line and quick to comment out when not needed:


print join("<br>",@arr);


Sorted:

print join("<br>",sort @arr);
10:10 pm on Aug 11, 2015 (gmt 0)

System Operator from US 

incredibill is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Jan 25, 2005
posts:14664
votes: 99


If you have complex arrays you might want to use the Data Dumper: [perldoc.perl.org...]

I tend to wrap the Perl Data Dumper output in <pre> so it formats nicely in a web page as so:

use Data::Dumper;
print '<pre>'.Dumper(@sfiles).'</pre>';


Additionally, to add one more sort method to those above:

On the WebmasterWorld Top 100 Poster page, I have an array with all posters and their total number of posts.

It's a hash array with items like this:

$maxposts{'incredibill'} = '15000';
$maxposts{'engine'} = '30000';
$maxposts{'brett_tabke'} = '45000';

So here I've got something I need sorted by the values, not the keys which is how it typically works.

To accomplish this, use the following which sorts from largest to smallest value:

foreach $user (sort { $maxposts{$b} <=> $maxposts{$a} } keys %maxposts) {
print "USER: $user POSTS: $maxposts{$user}<br>";
}


If you want them in reverse order, low to high, simply swap $a and $b as follows:

foreach $user (sort { $maxposts{$a} <=> $maxposts{$b} } keys %maxposts) {
print "USER: $user POSTS: $maxposts{$user}<br>";
}