You're part of the way there on creating a module to upload to CPAN. First make it object oriented so that this new module wouldn't need to export anything into peoples' namespaces. Clean up the code and indentation a little. Create some POD. Test it thoroughly. Upload it to CPAN, and you will have contributed to the greater community.
I took the liberty of creating an object oriented interface to your routine. I also changed the name of the "encoding" routine so that it looks more like a verb. I always just feel better when subs names relate to an action being taken. You would have to do some testing to make sure I didn't break anything, and you would have to create the POD markup. Feel free to alter the package name if you think it could be improved upon. Then put it up there for the world to use.
Here's my updated version:
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;
Dave
In reply to Re: Perl and Google Charts extended encoding
by davido
in thread Perl and Google Charts extended encoding
by PoliceCoP
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |