in reply to Re: Re: Can this If/Else be condensed into a 1 liner with a trailing If?
in thread Can this If/Else be condensed into a 1 liner with a trailing If?

Hmm. I thought it might be something like that, but now instead of a nebulous feeling that it must be something to do with returning values I actually know how it works! Very educational - thanks for the explanation. My subroutines will be grateful too.

So (just getting this straight, hoping my thought processes won't be too dull for others) in jerrygarciuh's case, if he replaces the if... else with
print "$in was not a number!"; input() unless $in =~ /\d/;
then the subroutine will return the number of characters chomped from $in, rather than $in itself. So in order to reduce the if... else loop to a single line, one wd have to do something like
sub input { my $arrayref=shift; print "\nSo far you've guessed @$arrayref." if $arrayref; print "\nWhat is your guess?\n"; chomp <STDIN>; my $in=<STDIN>; print "$in wasn't a number!";input() unless $in =~ /\d/; }
Would that work? Is it nicer? Have I learnt something from this exchange? (The answer to at least one of these questions is "yes".)

§ George Sherston

Replies are listed 'Best First'.
Re: Re: Re: Re: Can this If/Else be condensed into a 1 liner with a trailing If?
by suaveant (Parson) on Oct 03, 2001 at 18:17 UTC
    Actually, not quite... remember
    print "$in wasn't a number!";input() unless $in =~ /\d/; # is the same as print "$in wasn't a number!"; input() unless $in =~ /\d/; # what you want is print("$in wasn't a number!"),input() unless $in =~ /\d/;
    See, with the comma, the unless contains the print and the input, with the ; it only contains the input(), and I'm not sure what will be returned in that case, so I would probably do...
    print("$in wasn't a number!"),return input() unless $in =~ /\d/;
    Just to be safe. (It might work properly anyway, I'd have to test)

    It should return $in otherwise... I think... my rule of thumb usually is, if I am not sure what will be returned, I use a return. I usually only leave out the return when my value is on the actual last line of the subroutine. Can save headaches... :)

                    - Ant
                    - Some of my best work - Fish Dinner