-
#!/usr/bin/perl -w
-
use strict;
-
print "This program will convert Decimal to Binary \n";
-
print "Please pick your Decimal Number \n";
-
# Get the number from the command line or use default.
-
my $number = shift || <STDIN>;
-
printf "Binary Number ---- > %b\n", $number;
-
With the code above. I know it works. I am wonder how everything works.
What is "shift ||"?
What is printf.
Let me throw out some guesses.
With "printf "Binary Number ---- > %b\n", $number;" that is converting the $number into Binary because of the %b. Is this technical an array? print f seems like print with formula?
-
#!/usr/bin/perl -w
-
use strict;
-
print "Do you want a hex or octal \n";
-
my $hoo = <STDIN>;
-
chomp($hoo);
-
if ($hoo =~ /^hex$/) {
-
print "Please Type a Hex Number \n";
-
my $A = <STDIN>;
-
chomp($A);
-
print "\n";
-
print hex("$A")," <--- That is your Hex Number \n";
-
}
-
else {
-
print "Please Type a Octal Number\n";
-
my $AA = <STDIN>;
-
chomp($AA);
-
print "\n";
-
print oct("$AA")," <--- That is your Octal Number \n";
-
}
-
The only question I have about this code is "if ($hoo =~ /^hex$/)" What does the /^ $/ mean?
Thank you all that read this post.
To answer your first question, what the "||" does is specify an either or condition. In other words "shift off the next value from the @ARGV array (which holds the values fed as options to the script),
OR, if it is empty, then prompt the user for input".
As for printf, it is basically "print formatted". To get a better idea of how it all works, you can read the printf page on perldoc.perl.org, or better yet, look at the
sprintf page as it has a lot more detail.
As for what does "/^ $/" mean, you will have to delve into regular expressions for that. It is highly advised that you learn regular expressions as they are a big part of Perl and you will see them everywhere.
The / and / enclose the regular expression. The ^ specifies that the match will start at the beginning of the line and the $ specifies the end of the line. So, basically, the match in the code is looking for a line that ONLY contains the word "hex".
Regards,
Jeff