package Google::Charts::Encoding; # To use this: # my $enc = Google::Charts::Encoding->new( $string_to_encode ); # my $result = $enc->encode(); # To obtain the last result: # my $last_result = $enc->encoded(); # You may also pass the encode string to $enc->encode() # instead of to $enc->new(); # my $result = enc->encode( $string_to_encode ); use strict; use warnings; use POSIX; use List::Util qw[ min max ]; # Constructor: Pass the string to be encoded, or nothing (in which # case you must pass the string directly to $obj->encode() sub new { my $self = {}; $self->{encode_string} = $_[0] || undef; $self->{encoded} = undef; bless( $self ); return $self; } # If the string to be encoded was passed to $obj->new(), no # parameter is needed for calling $obj->encode(). If nothing # was passed to $obj->new(), you will need to pass the string # as a parameter here. sub encode { my $self = shift; my $to_encode = $_[0] || $self->{encode_string}; defined( $to_encode ) or die "Nothing to encode in __PACKAGE__ encode()\n"; my @characters = ( 'A' .. 'Z' , 'a' .. 'z', '0' .. '9', '-', '.' ); my @series = split( /\|/, $to_encode ); my @seriesmax = split( /\||\,/, $to_encode ); my $max = max( @seriesmax ); my $returnstring = ''; foreach ( @series ){ my @values = split( /\,/, $_ ); my $encoding = ''; foreach my $value ( @values ){ chomp $value; $value = ( $value / $max ) * 4095; my $first = floor( $value / 64 ); my $second = $value % 64; $encoding .= $characters[ $first ] . $characters[ $second ]; } $returnstring .= $encoding . ','; } my $encoded = substr( $returnstring, 0, -1 ); $self->{encoded} = $encoded; return $encoded; } # Getter for the most recent call to encode(). sub encoded { my $self = shift; if( defined( $self->{encoded} ) ) { return $self->{encoded} } else { die "Nothing has been encoded yet in __PACKAGE__\n"; } } 1;