Thanks. It works! But I want to understand why it works. Can you explain what is happening in this line? *{'update_' . $n }->(); download I thought glob is only used for directories.

The glob() function is used to search for files.

On the other hand, perl has many different types: scalars, arrays, hashes, etc. And a perl program can happily have variables named $x, @x, and %x, and it will run without error. A typeglob is one of the types in perl. The typeglob *x represents all variables named 'x' in your program, e.g. $x, @x, %x, sub x {}, etc. In order to understand typeglobs, you need to read perlreftut first, so that you know what references are.

The code fragment:

*{'update_' . $n }

resolves to the typeglob: *update_test. The arrow following the brackets:

*{'update_' . $n }->

...dereferences the reference on the left of the arrow. The type of dereference is determined by what's on the right of the arrow:

*{'update_' . $n }->()

In this case, the left side of the arrow, i.e. the typeglob, is treated as a reference to a subroutine, and the subroutine is called. Compare to this:

#####use strict; use warnings; use 5.010; sub greet { my $greeting = shift; say $greeting; } %greet = ( a => 'hello', b => 'goodbye', ); my $code_ref = \&greet; $code_ref->('hello'); my $hash_ref = \%greet; say $hash_ref->{b}; *greet->('goodbye'); say *greet->{a}; --output:-- hello goodbye goodbye hello

In reply to Re: Dynamically Calling a Subroutine by 7stud
in thread Dynamically Calling a Subroutine by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.