#!/usr/bin/perl -w # encode.pl - Don Yang (uguu.org) # # Run-length encode ASCII art image. # # 2014-07-12 use strict; use constant NO_RUN => 0; use constant SPACE => 1; use constant CHAR => 2; use constant NEWLINE => ord('!'); use constant SPACE_START => ord('#'); use constant SPACE_END => ord('['); use constant CHAR_START => ord(']'); use constant CHAR_END => ord('~'); sub Flush($$) { my ($type, $length) = @_; return unless $length > 0; if( $type == SPACE ) { print chr(SPACE_START - 1 + $length); } elsif( $type == CHAR ) { print chr(CHAR_START - 1 + $length); } } my $text = join '', <>; my $type = NO_RUN; my $length = 0; foreach my $c (unpack 'C*', $text) { if( $c == ord("\n") ) { # Newline Flush($type, $length); print chr(NEWLINE); $type = NO_RUN; $length = 0; } elsif( $c == ord(' ') ) { if( $type == SPACE ) { # Space -> space, extend current run if( $length == SPACE_END - SPACE_START + 1 ) { Flush($type, $length); $length = 1; } else { $length++; } } else { # Space -> char, flush previous run Flush($type, $length); $length = 1; $type = SPACE; } } else { if( $type == CHAR ) { # Char -> char, extend current run if( $length == CHAR_END - CHAR_START + 1 ) { Flush($type, $length); $length = 1; } else { $length++; } } else { # Char -> space, flush previous run Flush($type, $length); $length = 1; $type = CHAR; } } } # Flush final run Flush($type, $length); print "\n";