Vim script to fix the current file's package name

In our work project, there are lots of Test::Class-based modules, and they live in lib/ so other distributions can use them. Anyway, when writing a new module of tests, I don't start from an empty file but rather copy one of the existing test modules.

So I have to change the package name, but I've long felt that this can be automated - after all, if the module file is lib/Foo/Bar.pm, vim should be able to deduce that this is package Foo::Bar and change the package name accordingly.

The script below does that; it makes a few assumptions: that your modules live in a lib/ directory; that the package line already exists (but presumably with the wrong name) and that the package name to be replaced is in the first line that starts with 'package', followed by the name.

It's simple enough so you can adapt it to your needs. I hope you find this useful!

nnoremap <Leader>pa :<C-u>call PerlReplacePackageName()<CR>

function! PerlPackageNameFromFile()
    let filename = expand('%:p')
    let package = substitute(filename, '^.*/lib/', '', '')
    let package = substitute(package, '\.pm$', '', '')
    let package = substitute(package, '/', '::', 'g')
    return package
endfunction

function! PerlReplacePackageName()
    let package = PerlPackageNameFromFile()
    let pos = getpos('.')
    1,/^package\s/s/^package\s\+\zs[A-Za-z_0-9:]\+\ze\(\s\+{\|;\)/\=package/
    call setpos('.', pos)
endfunction

Thanks to kana1 for his corrections!

Leave a comment

About hanekomu

user-pic