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

Dear All,
I need a code to check a condition for which input have been got at runtime and replace a particular string if the condition satisfies.

For example, When the user inputs "Y", all "Example" should be made upper case. If the input is "N", then "Example" should be in lower case.

Please help.

Thanks
POP

Replies are listed 'Best First'.
Re: User input at runtime
by bobf (Monsignor) on Dec 13, 2007 at 05:04 UTC

    I'm not entirely sure what part you need help with. Could you post the code that you have (working or not) and be a little more specific?

    If you're starting from scratch, the following may help:

    • the angle bracket operator to read from STDIN (see I/O operators in perlop)
    • @ARGV - the array that holds parameters from the command line (see perlvar)
    • Getopt::Long or Getopt::Std - for more powerful handling of command line arguments
    • uc - to uppercase an expression
    • ucfirst - to uppercase the first letter of an expression
    • m// - for pattern matching (see perlop, and note the i modifier to match case-insensitively)
    • s/// - for pattern matching and replacing in a string(see perlop)
    • if...else blocks - to add conditionals to your program (see perlsyn)

    That should get you started. Good luck.

    Update: Added s///

Re: User input at runtime
by vivid (Beadle) on Dec 13, 2007 at 05:12 UTC

    Try this

    use strict; my $arg = $ARGV[0]; open(IN,"$arg")||die("Can't open the input file for reading"); undef $/; my $str = <IN>; close(IN); $/="\n"; print ("\nDo u want to Change Example to Uppercase:"); $value = <STDIN>; chomp($value); if ($value=~/^y$/){ $str=~s/\b(example)\b/uc($1)/gei; } open (OUT,">$arg")||die("Can't open the output file for writing"); print OUT $str; close(OUT);

    Vivid

      Thank you very much VIVID...
      This stuff works as per my requirement....

      Thanks
      POP
        This doesn't bode well for your High School midterm...
Re: User input at runtime
by poolpi (Hermit) on Dec 13, 2007 at 07:41 UTC
    The Damian CONWWAY's module can help you :
    http://search.cpan.org/~dconway/IO-Prompt-v0.99.4/lib/IO/Prompt.pm
    #!/usr/bin/perl use strict; use warnings; use IO::Prompt; my $example = "Example"; ( prompt "Enter your choice [y/n] : ", -yes_no ) ? print uc($example), "\n" : print lc($example), "\n";
    OUTPUT : Enter your choice [y/n] : y EXAMPLE Enter your choice [y/n] : n example Enter your choice [y/n] : (Please answer 'y' or 'n')
    HTH,
    PooLpi