Perl graph

This Perl example function shows how to generate a graph from a array.

#!/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:

   ^                               
 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

2 thoughts on “Perl graph”

  1. 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.

  2. 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.

Leave a Reply

Your email address will not be published.

1 × 4 =