ascii_encode_decode.pl 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 25 July 2012
  5. # https://github.com/trizen
  6. # A simple ASCII encoder-decoder.
  7. # What's special is that you can delete words from the encoded text, and still be able to decode it.
  8. # You can also insert or append encoded words to an encoded string and decode it later.
  9. use 5.010;
  10. use strict;
  11. use warnings;
  12. sub encode_decode ($$) {
  13. my ($encode, $text) = @_;
  14. my $i = 1;
  15. my $output = '';
  16. LOOP_1: foreach my $c (map { ord } split //, $text) {
  17. foreach my $o ([32, 121]) {
  18. if ($c > $o->[0] && $c <= $o->[1]) {
  19. my $ord =
  20. $encode
  21. ? $c + ($i % 2 ? $i : -$i)
  22. : $c - ($i % 2 ? $i : -$i);
  23. if ($ord > $o->[1]) {
  24. $ord = $o->[0] + ($ord - $o->[1]);
  25. }
  26. elsif ($ord <= $o->[0]) {
  27. $ord = $o->[1] - ($o->[0] - $ord);
  28. }
  29. $output .= chr $ord;
  30. ++$i;
  31. next LOOP_1;
  32. }
  33. }
  34. $output .= chr($c);
  35. $i = 1;
  36. }
  37. return $output;
  38. }
  39. my $enc = encode_decode(1, "test");
  40. my $dec = encode_decode(0, $enc);
  41. say "Enc: ", $enc;
  42. say "Dec: ", $dec;
  43. # Encoding
  44. my $encoded = encode_decode(1, "Just another ")
  45. . encode_decode(1, "Perl hacker,");
  46. # Decoding
  47. my $decoded = encode_decode(0, $encoded);
  48. say $encoded;
  49. say $decoded;