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

In Perl 5.010, I'd like to write:
my $suffix = given ($type) { when ("csv") { "txt" } when ("xml") { "xml" } };
I know I can effectively accomplish the same thing with a do statement and introducing a dummy lexical:
my $suffix = do { my $result; given ($type) when ("csv") { $result = "txt" } when ("xml") { $result = "xml" } ... } $result };
Is there another way to use given...when... in a "functional" way which avoids introducing a do statement and a dummy lexical?

Replies are listed 'Best First'.
Re: functional "given...when..."?
by BrowserUk (Patriarch) on Mar 15, 2010 at 19:43 UTC

    Making it data driven would be easier to maintain:

    my %suffixes = ( csv => 'txt', xml => 'xml', ); my $type = ...; my $suffix = $suffixes{ $type };

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      In general I'd like to use the full power of smart matching.
Re: functional "given...when..."?
by almut (Canon) on Mar 15, 2010 at 20:02 UTC

    Just for kicks you could write

    my $suffix = sub { given ($type) { when ("csv") { return "txt" } when ("xml") { return "xml" } }}->();

    (in which case you can't use continue, of course)

Re: functional "given...when..."?
by JavaFan (Canon) on Mar 16, 2010 at 11:32 UTC
    You can of course write:
    my $suffix = $type ~~ "csv" ? "txt" : $type ~~ "xml" ? "xml" : ....;
    No do, no extra variable.
Re: functional "given...when..."?
by JavaFan (Canon) on Mar 16, 2010 at 11:30 UTC
    Is there another way to use given...when... in a "functional" way which avoids introducing a do statement and a dummy lexical?
    No, in the same way you cannot do
    my $r = if ($foo) then {"bar"} else {"baz"};
    or
    my $r = for (1, 2, 3) {$_ + 4};
    But you can in ALGOL 68! ;-)

      I guess he was hoping that given when would work line if/then:

      print do{ if( $_ ){ 'foo' }else{ 'bar' } } for 0,1;; bar foo

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.