Skip to content

Instantly share code, notes, and snippets.

@tyru
Created Apr 7, 2010
Embed
What would you like to do?
camelize/decamelize in Perl without String::CamelCase.
#!/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>
@rvosa
Copy link

rvosa commented Oct 19, 2018

I think there might be an off-by-one error on line 27, where the substring index should start at 0.

@gpaulissen
Copy link

gpaulissen commented Dec 17, 2018

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