On Mon, Sep 12, 2011 at 2:55 PM, Ryan Munson
<ryan.barrac...@elboardo.com> wrote:
> I am running through a good book on Perl and am having some issues with a
> script I am trying to create for one of the practice exercises (I am
> teaching myself Perl for work). Just to let you know the solution does not
> involve using an if statement because this is in the next chapter.

What have you learned so far? This seems a little advanced to do
before you even know how to use an if statement, unless the book has
already explained the solution and just wants for you to type it out.

> The objective is to "Write a program that asks for a decimal less than 256
> and converts it to binary."
*snip*
> chomp(my $dec = <STDIN>);
> $dec = $dec < 256;

I doubt that this is doing what you intended it to do. The < operator
is a comparison operator (numeric less-than operator) and will return
a boolean result indicating whether or not the left-hand side is
less-than the right-hand side in a numeric context. You're overwriting
your $dec variable with this boolean result, meaning it will either
contain '' (equivalent to zero) or 1 after this statement. You can
confirm this with a simple print statement:

print STDERR "After the less-than operation \$dec = $dec ... :(\n";

> print $dec, "is less than 256! ", "\n";

This looks like the kind of print statement that you would have
/inside/ of an if statement i.e., only if some condition is true, such
as the less-than operation seen erroneously on the previous line.
Perhaps the previous line was supposed to be an if statement? That
would seem to contradict you not being taught about if statements yet,
however.

> $dec = oct($dec);

There are two problems with this line. Firstly, oct refers to the
octal numbering system, which is not the same as the binary numbering
system. (Reading the perldoc, however, I'm surprised to learn that it
can also handle hexadecimal and binary strings, so perhaps this
inconsistency isn't really a problem at all). Secondly, oct doesn't
convert a number to an octal string; rather it converts an octal
string to a number. :) You can see for yourself with the following
command: perldoc -f oct.

You can also see with this simple program:

#!usr/bin/perl

use strict;
use warnings;

# Outputs 8 instead of 12 (the octal number for decimal 10)
# or 10 or whatever other number you might otherwise expect.
print oct(10), "\n";

__END__

Rethink the exercise and what you've learned and let us know if you
still need help. :)


-- 
Brandon McCaig <http://www.bamccaig.com/> <bamcc...@gmail.com>
V zrna gur orfg jvgu jung V fnl. Vg qbrfa'g nyjnlf fbhaq gung jnl.
Castopulence Software <http://www.castopulence.org/> <bamcc...@castopulence.org>

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to