This Perl example function shows how to generate a graph from a array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#!/usr/bin/perl use strict; #example data my @arr = (1,7,2,12,5,10,11,6,9); #test sub print graph(1, 1, 2, 3, 5, 8, 13,).$/; print graph(@arr).$/; #graph sub sub graph { my @arr = @_; my $height = $arr[0]; for(@arr){ if($_ > $height){ $height = $_; } } my $out = " ^".$/;; for(my $y = $height;$y > 0;--$y){ $out .= len_format($y."|",4); for my $x (0..$#arr){ if(($arr[$x])-$y >= 0){ $out .= len_format("*",3); }else{ $out .= len_format(" ",3); } } $out .= $/; } for(-2..$#arr){$out .= "---";} $out .= ">".$/." "; for(@arr){$out .= len_format($_,3);} return($out.$/); } #format strings sub len_format{ my $str = shift; my $len = shift; return((" "x($len-length($str))).$str); } |
The sub returns this result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
^ 13| * 12| * 11| * 10| * 9| * 8| * * 7| * * 6| * * 5| * * * 4| * * * 3| * * * * 2| * * * * * 1| * * * * * * * ---------------------------> 1 1 2 3 5 8 13 ^ 12| * 11| * * 10| * * * 9| * * * * 8| * * * * 7| * * * * * 6| * * * * * * 5| * * * * * * * 4| * * * * * * * 3| * * * * * * * 2| * * * * * * * * 1| * * * * * * * * * ---------------------------------> 1 7 2 12 5 10 11 6 9 |
Your style is really unique compared to other people I have read
stuff from. Thank you for posting when you have the opportunity,
Guess I will just bookmark this page.
Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically
tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some
time and was hoping maybe you would have some experience with something like this.
Please let me know if you run into anything. I truly enjoy reading your
blog and I look forward to your new updates.