Logicus has asked for the wisdom of the Perl Monks concerning the following question:

Ok, I have a question. Just from intellectual curiosity rather than any actual pressing need for a solution, I am wondering thusly...

Given that the following aXML code fragment:

<given g="somevalue"> <foo> [get_file]foo[/get_file] </foo> <bar> [get_file]bar[/get_file] </bar> <else> [get_file]baz[/get_file] </else> </given>

Is functionally identical to the following Modern::Perl code fragment :

given ("somevalue") { when (/foo/) { return get_file('foo'); } when (/bar/) { return get_file('bar'); } default { return get_file('baz'); } }

What then would be the Perl equivalent of this fragment :

<given g="somevar"> <get_file>cases</get_file> </given>

Where the file "cases" contains the same data as existed inside the given tag of the original fragment, and is dynamically loaded prior to the given tag being processed?

Replies are listed 'Best First'.
Re: Dynamic given statement
by CountZero (Bishop) on Oct 21, 2011 at 20:34 UTC
    If the content of cases cannot be known at compile time, then you have to use eval to compile the string containing cases during run-time.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

      So something like:

      my $cases = get_file('cases'); eval qq@ given ('somevar') { $cases } @;

      Ewww ugly!! Given how dog-awful slow eval is, I've done my utmost to completely remove it from my lexicon! I think there is only one place in my new system where it appears and then its only invoked if for some reason I have to embed raw Perl into my documents. (I believe that that can be completely avoided tbh)

        Not sure I follow you altogether but it seems what you want to do is something like:

        while(my $thing = input()){ my $consequence = given_thing($thing,\&get_file,qw(foo bar baz)); ## accept the consequences of your actions ... } sub given_thing { my ($thing,$action,@keys) = @_; do { $thing ~~ $_ and return $action->($thing)} for @keys; }

        I wouldn't be too quick to throw eval away. Sure it is slow and a security risk but the ability to dynamically create executable perl can significantly shorten the road from here to there.