Created
April 7, 2010 09:45
-
-
Save tyru/358703 to your computer and use it in GitHub Desktop.
camelize/decamelize in Perl without String::CamelCase.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use utf8; | |
use Test::More; | |
sub camelize { | |
my ($s) = @_; | |
$s =~ s{(\w+)}{ | |
($a = lc $1) =~ s<(^[a-z]|_[a-z])>< | |
($b = uc $1) =~ s/^_//; | |
$b; | |
>eg; | |
$a; | |
}eg; | |
$s; | |
} | |
sub decamelize { | |
my ($s) = @_; | |
$s =~ s{(\w+)}{ | |
($a = $1) =~ s<(^[A-Z]|(?![a-z])[A-Z])>< | |
"_" . lc $1 | |
>eg; | |
substr $a, 1; | |
}eg; | |
$s; | |
} | |
is camelize('snake_case'), 'SnakeCase'; | |
is decamelize('CamelCase'), 'camel_case'; | |
is decamelize(camelize('snake_case')), 'snake_case'; | |
is camelize(decamelize('CamelCase')), 'CamelCase'; | |
done_testing | |
__END__ | |
=head1 NAME | |
perl.pl - NO DESCRIPTION YET. | |
=head1 SYNOPSIS | |
=head1 OPTIONS | |
=head1 AUTHOR | |
tyru <tyru.exe@gmail.com> |
I used this snippet for converting a grammar wth mixed case parser tokens to ANTLR4 tokens (only lowercase allowed with underscores and digits) so I added somes tests:
is decamelize('lexer'), 'lexer';
is decamelize('LexerIATA'), 'lexer_iata';
For that I needed to change the decamelize function to
sub decamelize {
my ($s) = @;
$s =~ s{([a-zA-Z][a-zA-Z0-9]*([a-z0-9]|\b))}{
my $replaced = 0;
($a = $1) =~ s<(^[A-Z]+|(?![a-z])[A-Z]+)><
$replaced = 1;
"_" . lc $1;
>eg;
($replaced ? substr $a, 1 : $a);
}eg;
$s;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think there might be an off-by-one error on line 27, where the substring index should start at 0.