Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.vimrc to automatically compile perl code, based on actual perl version

Tags:

vim

perl

My .vimrc is configured to automatically compile my Perl script upon save. However, it is hard-coded to perl 5.14.
Some of the scripts I maintain are 5.8.8, and others are 5.16
I would like vim to compile my code based on the version in the hashbang #! line
Is this possible?

Here is my current .vimrc:

" check perl code with :make
"     by default it will call "perl -c" to verify the code and, if there are any errors, the cursor will be positioned in the offending line.
" errorformat uses scanf to extract info from errors/warnings generated by make.
"     %f = filename  %l = line number  %m = error message
" autowrite tells vim to save the file whenever the buffer is changed (for example during a save)
" BufWritePost executes the command after writing the buffer to file
" [F4] for quick :make
autocmd FileType perl set makeprg=/home/utils/perl-5.14/5.14.1-nothreads-64/bin/perl\ -c\ %\ $*
autocmd FileType perl set errorformat=%f:%l:%m
autocmd FileType perl set autowrite
autocmd BufWritePost *.pl,*.pm,*.t :make 
like image 405
Chris Koknat Avatar asked Dec 04 '25 08:12

Chris Koknat


1 Answers

You have to dynamically change the Perl path in 'makeprg' based on the shebang line. For example:

:let perlExecutable = matchstr(getline(1), '^#!\zs\S\+')
:let perlExecutable = (empty(perlExecutable) ? '/home/utils/perl-5.14/5.14.1-nothreads-64/bin/perl' : perlExecutable) " Default in case of no match
:let &makeprg = perlExecutable . ' -c % $*'

You can invoke that (maybe encapsulated in a function) on the FileType event, but then it won't properly detect new files that don't have the shebang yet. Or prepend the call to your autocmd BufWritePost *.pl,*.pm,*.t :make; that will re-detect after each save.


PS: Instead of all those :autocmd FileType in your ~/.vimrc, I would rather place those in ~/.vim/after/ftplugin/perl.vim (if you have :filetype plugin on). Also, you should use :setlocal instead of (global) :set.

like image 113
Ingo Karkat Avatar answered Dec 06 '25 01:12

Ingo Karkat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!