in reply to Subroutines within if statements

Another way to do it would be to use a regular expression match.

use strict; use warnings; print "Would you like to add or remove symbolic links?\n"; chomp( my $answer = <STDIN> ); if( $answer =~ m{^a(?:dd)?$} ) { addlinks(); } elsif( $answer =~ m{^r(?:emove)?$} ) { rmlinks() } else { exit( 0 ); }

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Subroutines within if statements
by runrig (Abbot) on Feb 21, 2008 at 22:37 UTC
    A simple and more flexible (for the user) way would be to reverse the args:
    if ( "add" =~ /^\Q$answer/ ) { ... }
    Update: you can even precompile the regex for multiple uses:
    my $ans = qr/^\Q$answer/; if ( "add" =~ /$ans/ ) { ... } elsif ( "remove" =~ /$ans/ ) { ... }
Re^2: Subroutines within if statements
by ikegami (Patriarch) on Feb 21, 2008 at 22:48 UTC

    chomp isn't needed if you use "$" in your regexp.

    Conversely, "\z" is sufficient if chomp is used.