Advertisement
DRVTiny

Untitled

Sep 13th, 2017
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.73 KB | None | 0 0
  1. use 5.16.1;
  2. use Exporter qw(import);
  3.  
  4. our @EXPORT=qw{sexpr sexpr2txt};
  5. our @EXPORT_OK=@EXPORT;
  6.  
  7. sub sexpr
  8. {
  9.         my @stack = ([]);
  10.         local $_ = $_[0];
  11.  
  12.         while (m{
  13.                 \G    # start match right at the end of the previous one
  14.                 \s*+  # skip whitespaces
  15.                 # now try to match any of possible tokens in THIS order:
  16.                 (?<lparen>\() |
  17.                 (?<rparen>\)) |
  18.                 (?<FLOAT>[0-9]*+\.[0-9]*+) |
  19.                 (?<INT>[0-9]++) |
  20.                 (?:"(?<STRING>([^\"\\]|\\.)*+)") |
  21.                 (?<IDENTIFIER>[^\s()]++)
  22.                 # Flags:
  23.                 #  g = match the same string repeatedly
  24.                 #  m = ^ and $ match at \n
  25.                 #  s = dot and \s matches \n
  26.                 #  x = allow comments within regex
  27.                 }gmsx)
  28.         {
  29.                 die "match error" if 0+(keys %+) != 1;
  30.  
  31.                 my $token = (keys %+)[0];
  32.                 my $val = $+{$token};
  33.  
  34.                 if ($token eq 'lparen') {
  35.                         my $a = [];
  36.                         push @{$stack[$#stack]}, $a;
  37.                         push @stack, $a;
  38.                 } elsif ($token eq 'rparen') {
  39.                         pop @stack;
  40.                 } else {
  41.                         push @{$stack[$#stack]}, bless \$val, $token;
  42.                 }
  43.         }
  44.         return $stack[0]->[0];
  45. }
  46.  
  47. sub squote
  48. { (local $_ = $_[0]) =~ /[\s\"\(\)]/s ? do{s/\"/\\\"/gs; qq{"$_"}} : $_; }
  49.  
  50. sub sexpr2txt
  51. {
  52.        qq{(@{[ map {
  53.                ref($_) eq '' ? squote($_) :
  54.                ref($_) eq 'STRING' ? squote($$_) :
  55.                ref($_) eq 'ARRAY' ? sexpr2txt($_) : $$_
  56.        } @{$_[0]} ]})}
  57. }
  58.  
  59. 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement