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

#!/bin/perl use strict; use warnings; use diagnostics; use Term::ANSIColor; use JSON; use Data::Dumper; open(my $fh, '<', '/home/david/dev/linux.json'); my $json_text = <$fh>; my $test_scalar = decode_json($json_text); my $max = 10; my $count = 0; my $quit = 0; sub reddit { while ($count <= $max) { print colored ['red'], "-> $test_scalar->{data}{childr +en}[$count]{data}{title}\n"; print colored ['yellow'], "$test_scalar->{data}{childr +en}[$count]{data}{url}\n"; $count++; } } reddit(); my $wait = <STDIN>; chomp($wait); if ($wait eq '\cR') { reddit(); }

I have a problem with executing a subroutine when an IF-statement evaluates to true. What am I doing wrong? The only thing that happends when I press control+r is that the script exits. The code isn't pretty, any pointers on how to make this code prettier are welcome! Regards, David

Replies are listed 'Best First'.
Re: Executing a subroutine in an IF
by morgon (Priest) on Jun 16, 2012 at 00:12 UTC
    First: '\cR' is NOT control-R - it is a three character string.

    You want double-quotes: "\cR"

    And you cannot read a control-r just like that. You need to put your terminal into raw mode which you can do via Term::ReadKey:

    use strict; use Term::ReadKey; ReadMode 4; # raw mode my $key = ReadKey(0); # read a character ReadMode 0; # back to normal mode if($key eq "\cR") { # do whatever you want to do print "got ctrl-R!\n"; }
      Hi morgon, Thank you for the answer. Reading the key works just fine now, but the sub still won't execute. I feel as if this should work .. read the key, if it's ctrl-r then execute the subroutine. Am I missing something crucial here? Regards, David

        I feel kind of foolish now, I forgot to reset the $count scalar to 0 before calling the subroutine again. It works as intended now. :-)

        #!/bin/perl use strict; use warnings; use diagnostics; use Term::ANSIColor; use Term::ReadKey; use JSON; open(my $fh, '<', '/home/david/dev/linux.json'); my $json_text = <$fh>; my $test_scalar = decode_json($json_text); my $max = 10; my $count = 0; sub reddit { while ($count <= $max) { print colored ['red'], "-> $test_scalar->{data}{childr +en}[$count]{data}{title}\n"; print colored ['yellow'], "$test_scalar->{data}{childr +en}[$count]{data}{url}\n"; $count++; } } reddit(); ReadMode 4; my $wait = ReadKey(0); ReadMode 0; if ($wait eq "\cR") { $count = 0; reddit(); }