# Emacs inserting boilerplate twice

I have an entry that is basically identical to the one found here:

(defun perl-boilerplate ()
(if (not (file-exists-p (buffer-file-name (current-buffer))))
(cond
((string-match "\.pl$" buffer-file-name) (insert "#!/usr/local/bin/perl\nuse warnings;\nuse strict;\n")) ((string-match "\$$[^/]*\$$\.pm$" buffer-file-name)
(insert
(concat "package " (match-string 1 buffer-file-name)
";\n\nuse warnings;\nuse strict;\n\n1;\n"))
(backward-char 4)))))



...this all worked fine when I was using 22.3 on OS X. I just updated to 24.1, and now, whenever I create a new .pl file, the boilerplate inserts twice. My .emacs file didn't change, so I'm wondering what causes this: is the hook being applied twice? (Didn't think that could happen.)

Anyone encounter the same phenomenon, or can tell me how to fix this?

Also

Here's what happens when I start a module. Note how the second instance is added before the first one finishes--i.e., before it adds the closing '1;' line.

package Foo;

use warnings;
use strict;
# $Id$

package Foo;

use warnings;
use strict;
# $Id$

1;

1;


Update

It appears to be a difference in the cperl-mode.el file that shipped with 22.3 and 24.1, although I don't know exactly where. (The diff is 1,124 lines.) But swapping out the old and new files (and removing the compiled .elc file) returned the behavior to what I wanted.

-
What happens if you comment out the add-hook line? –  choroba Jul 19 '12 at 10:12
If I comment out add-hook, no boilerplate gets added at all. –  amp108 Jul 19 '12 at 17:36
Seems like the .emacs file is being evaluated twice, therefore the boilerplate is being added to the hook two times. I have no idea why this could happen. –  choroba Jul 20 '12 at 6:03

(would rather leave this as a comment - but I seem to lack the rep - I'll remove this answer when a real answer is given)

Seems one of two things are likely happening

• after your .emacs is evaluated cperl-mode-hook has your perl-boilerplate function listed in it twice. (as mentioned above in a comment)
• the new version of cperl is running the cperl-mode-hook twice.

To debug the first case use CTRL-H v to see the value of cperl-mode-hook when you've opened a new file and it has doubled the boilerplate.

To debug the second case you could add another function to the hook which uses message to print out something (like 'HELLO from cperl-mode-hook') then check the *Messsages* buffer to see how many times you see it after visiting a new file.

Given that the problem seems to go away when you downgrade to the old version of cperl then it seems likely that it is the second problem.

You might be able to fix the second problem by createing a buffer-local-variable and checking if it is set before inserting the boilerplate - thus keeping it from being inserted twice.