title: Check if subroutine exists in Perl
body: <p>I would like to check if a subroutine exists before calling it. For example:</p>
  
  <pre><code>use warnings;
  use strict;
  
  my @names=qw (A B);
  
  for (@names) {
    my $sub=\&amp;{"print$_"};
    if (exists &amp;{$sub}) {
      &amp;$sub();
    }
  }
  
  sub printA {
    print "hello A\n";
  }
  </code></pre>
  
  <p>However this code does not work. It gives error:</p>
  
  <pre><code>Undefined subroutine &amp;main::printB
  </code></pre>
  
  <p>I know that I can use <code>eval</code>,</p>
  
  <pre><code>for (@names) {
    my $sub=\&amp;{"print$_"};
    eval {
      &amp;$sub();
    };
    if ($@) {
      print "$_ does not exist..\n";
    }
  }
  </code></pre>
  
  <p>This is fine, but it would be nice to know why the first code did not work?</p>