Perl scalars as numbers or character strings

P

Paul E. Schoen

I am trying to understand scalar variables, and I found the following:
http://www.tutorialspoint.com/perl/perl_scalars.htm

Here is an excerpt:

#!/usr/bin/perl

$number = "5";
$exponent = "2 ** 8";
$string = "Hello, PERL!";
$float = 12.39;

# We can also assign a scalar an empty (undefined) value:
$nothing = undef;

# Printing all the above values
print "$number\n";
print "$exponent\n";
print "$string\n";
print "$float\n";
print "There is nothing: $nothing\n";

This will give following result
5
2 ** 8
Hello, PERL!
12.39
There is nothing:

My question is whether $number, $exponent, and $float are actually numbers
or character strings, particularly those that are enclosed in quotes. Thus,
what would be the result of:

$mynum = $number * $float;
print "$mynum";
print $mynum;
$mynum = 2 ** 8;
print "$mynum"

And what happens if you add characters and variables in a print statement?

print "This is a number$mynum2";

The information in the FAQ did not seem to address this except as follows:

my $string = '0644';

print $string + 0; # prints 644

print $string + 44; # prints 688, certainly not octal!

It seems like the printf and sprintf functions work as I would expect,

printf "0%o %d", $number, $number;

But what happens if you use the following:

$number = "0123";
$number = "A123";
$number = "one";
$number = 123;
$number = 123 + 4.56;
$number = "123 + 4.56";
$number = "123" + "4.56";

Sorry for the noobish questions, but I am used to C and Delphi Pascal,
where I am familiar with the syntax.

Thanks,

Paul
 
S

sln

I am trying to understand scalar variables, and I found the following:
http://www.tutorialspoint.com/perl/perl_scalars.htm

Here is an excerpt:

WARNING!!! You do not have strick/warnings turned on!
#!/usr/bin/perl

$number = "5";
$exponent = "2 ** 8";
$string = "Hello, PERL!";
$float = 12.39;

# We can also assign a scalar an empty (undefined) value:
$nothing = undef;

# Printing all the above values
print "$number\n";
print "$exponent\n";
print "$string\n";
print "$float\n";
print "There is nothing: $nothing\n";

Warning, undefined value in print!
This will give following result
5
2 ** 8
Hello, PERL!
12.39
There is nothing:

My question is whether $number, $exponent, and $float are actually numbers
or character strings,

No and Yes. But if you continue to try to confuse yourself by naming the
variables what you think they contain, you've already lost the war on the
understanding of Perl.
particularly those that are enclosed in quotes. Thus,
what would be the result of:

$mynum = $number * $float;
print "$mynum";
print $mynum;
$mynum = 2 ** 8;
print "$mynum"

And what happens if you add characters and variables in a print statement?

print "This is a number$mynum2";
The context of the variable as used in the print statement at the time it is
parsed will be used.
The information in the FAQ did not seem to address this except as follows:

my $string = '0644';

print $string + 0; # prints 644

print $string + 44; # prints 688, certainly not octal!

if ($string * 1 == 644) {
print "string + 44 = ", $string + 44, "\n";
}
It seems like the printf and sprintf functions work as I would expect,

printf "0%o %d", $number, $number;

But what happens if you use the following:

$number = "0123";
$number = "A123";
$number = "one";
$number = 123;
$number = 123 + 4.56;
$number = "123 + 4.56";
$number = "123" + "4.56";

Sorry for the noobish questions, but I am used to C and Delphi Pascal,
where I am familiar with the syntax.

Thanks,

Paul

Its all how you use it. Use it as a string, its a string. Number, a number.
It appears Perl uses a few representations of the same variable, it appears.

-sln
 
S

Steve C

Paul said:
My question is whether $number, $exponent, and $float are actually numbers
or character strings, particularly those that are enclosed in quotes. Thus,
what would be the result of:

What do you mean by "actually"?
perl -e '$num=5; $str="5"; print "actually" if $num == $str'
actually
Sorry for the noobish questions, but I am used to C and Delphi Pascal,
where I am familiar with the syntax.

You can't learn perl from a C manual. Be that as it may, in C I can do:

double d;
d = 5; /* Wait! I thought 5 was an integer! What's going on? */

perl is like C with a much smarter compiler.
 
S

sln

What do you mean by "actually"?
perl -e '$num=5; $str="5"; print "actually" if $num == $str'
actually


You can't learn perl from a C manual. Be that as it may, in C I can do:

double d;
d = 5; /* Wait! I thought 5 was an integer! What's going on? */

perl is like C with a much smarter compiler.

Not exactly, Perl is like C, with a structural variant representation
of values per variable.

-sln
 
S

sln

As a simple example, a Perl variable is a C structure containing
types (a union if you will), where the particular code usage is
determined at parstime (and will vary in different parts of the code),
and determined at runtime (mostly).

So like:
var variable {
char *;
int;
float;
...
}

If the particular spot in the code is used as a string,
it will use char *. If that is empty, it will grab int or float
and convert it to char *, assign it to char * (in the structure)
and use it dynamically at run time.

The same goes for all the other variants. In this regard its no
different than any typless language, say like JScript. There are rules
and defaults as always, as it percolates up to the parser and runtime
engine.

-sln
 
U

Uri Guttman

as for you, how you are learning perl is bizarre given your claim to
know c and other langs. do you know shell at all? awk even? unix in
general? perl is best understood as being born of that environment
(including c) and stealing the best of breeds from each.

PES> I am trying to understand scalar variables, and I found the following:
PES> http://www.tutorialspoint.com/perl/perl_scalars.htm

yeah! i haven't done this in a while and i am in the mood for it. i have
found extremely few perl tutorials on the net worth a single bit of
space. i have done reviews (google for them) and i need to vent some on
this one.


i moved this to the top so you can read my summary.

i have to stop now. of course i can go on. there is lots here and some
of it is useful but as typical there is poor writing and too many
mistakes, misconceptions, inaccuracies. what is needed for all those web
tutes on perl is a good editor. they never seem to be written by someone
active in the perl community as they would have gotten useful feedback
that way. given the free beginning perl book and perl's own great
documentation (including many tutorials now) why these web tutes still
are found is beyond me.

uri

from the scalars page:

$number = "5";

that is a string, not a number

$exponent = "2 ** 8";
$string = "Hello, PERL!";
$float = 12.39;

# We can also assign a scalar an empty (undefined) value:
$nothing = undef;

it prints:

There is nothing:


the empty string is more appropriate as it won't trigger a warning.

from the page on arrays:

@10 = (1 .. 10);
@100 = (1 .. 100;
@1000 = (100 .. 1000);

using numbers for var names works but is dumb as hell.

@abc = (a .. z);

the last one will warn on unquoted strings

print "@10"; # Prints number starting from 1 to 10
print "@100"; # Prints number starting from 1 to 100
print "@1000"; # Prints number starting from 1 to 1000

the comment should be from 100. and do you want to print 900 numbers on
one line for a demo?

print "@abc"; # Prints number starting from a to z

that is not a number.

When adding elements using push() or shift() you must specify
two arguments, first the array name and second the name of the
element to add.

wrong. push and unshift take a list of elements to add to the array. and
you don't pass in the array name but the array variable. and what is the
'name of the element to add'? how would i push 1 as it has no name? or
an anon reference which has no name?


from the Object Oriented section:

Within Perl, an object is merely a reference to a data type that
knows what class it belongs to. The object is stored as a
reference in a scalar variable. Because a scalar only contains a
reference to the object, the same scalar can hold different
objects in different classes.

that is sara palin logic! what about a hash element holding an object?
what does different classes have to do with a single reference? it is
just the ability of a scalar value to be a reference to a blessed object
that is the core of perl's object flexibility.

Perl provides a bless() function which is used to return a
reference and which becomes an object.

bless associates a perl datum to a class. it is passed in a reference to
that datum and returns it. it does not create the reference which is
what the above statement implies.

the list of topics has this whopper!

Perl Error Handeling

how does he handle that error? :)

from the Perl IF..ELSE.. section (sic)

The final conditional statement is actually an operator.the
conditional operator. It is synonymous with the if...else
conditional statement but is shorter and more compact. The
format for the operator is:

(expression) ? (statement if true) : (statement if false)

huh? those are expressions, not statements. teaching that is the way to
get nasty precedence issues with ?:.

For example, we can emulate the previous example as follows:

($date == $today) ? print "Happy B.Day!\n" : print "Happy Day!\n";

and he doesn't even obey the previous style as () were not used. it will
work here because : is low binding but if you put an assignment in there
it breaks without the parens. also it subverts the purpose of ?: which
is to return a value based on a condition, not to do side effects. that
would better be written as:

print ($date == $today) ? "Happy B.Day!\n" : "Happy Day!\n";

which removes the redundant print calls, is shorter and proper.

from the operators page (edited a bit):

There are many Perl operators but here are a few of the most
common ones:

Arithmetic Operators

+ addition
- subtraction
* multiplication
/ division

Numeric Comparison Operators

== equality
!= inequality

String Comparison Operators

le less than or equal
ge greater than or equal

the comparison ops are the most common ops? who uses ge and le often?? i
can't recall the last time i actually used those!!

the only other text on this page is a copy of the precedence
table. that's it. basic math, comparison ops and then precedence with
nothing on any other ops.


from the regular expressions page:

There are three regular expression operators within Perl

* Match Regular Expression - m//
* Substitute Regular Expression - s///
* Transliterate Regular Expression - tr///

this is a classic tutorial laugher, calling tr/// a regex op.

the rest of this page has minimal explanations of regexes but a table of
all the modifiers. it shows $1 being used but with no explanation. there
is a minimal cheat sheet on character classes, anchors, etc.

it covers ?PATTERN? which is rarely used and newbies will not want to
learn about it. it is used mostly in more complex parsers and such to
match only one time.

so you could read perlretut and perlrequick and learn more from better
and more accurate writing.

uri
 
S

sln

as for you, how you are learning perl is bizarre given your claim to
know c and other langs. do you know shell at all? awk even? unix in
general? perl is best understood as being born of that environment
(including c) and stealing the best of breeds from each.

Whats your claim, apparently you know everything, sort of a jack-off
of all trades.

-sln
 
U

Uri Guttman

s> Whats your claim, apparently you know everything, sort of a jack-off
s> of all trades.

i know enough to not help you get a perl job. that is all i need to
know.

uri
 
S

sln

s> Whats your claim, apparently you know everything, sort of a jack-off
s> of all trades.

i know enough to not help you get a perl job. that is all i need to
know.

uri

I work for Google as a Perl manager. Don't let your resume pass my desk!

-sln
 
P

Paul E. Schoen

Uri Guttman said:
as for you, how you are learning perl is bizarre given your claim to
know c and other langs. do you know shell at all? awk even? unix in
general? perl is best understood as being born of that environment
(including c) and stealing the best of breeds from each.

I think I have a general aversion to languages that make assumptions about
variables, and that includes JavaScript and VB. I know enough C and Delphi
to make fairly complex Windows GUI applications that operate on a nearly
real-time basis with serial communication and data analysis, and I use a
version of C for some PIC projects, but mostly I use assembly.

I don't know shell. I found this:
http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html

I have seen awk programs. I am not familiar with the syntax.

I know a few unix commands and I have used FTP and Telnet, but that's about
it. It seems similar to MSDOS but with more powerful features (like grep).

PES> I am trying to understand scalar variables, and I found the
following:
PES> http://www.tutorialspoint.com/perl/perl_scalars.htm

yeah! i haven't done this in a while and i am in the mood for it. i have
found extremely few perl tutorials on the net worth a single bit of
space. i have done reviews (google for them) and i need to vent some on
this one.

Thanks for the warnings about on-line tutorials and other sources of
information. Even I found an error where a /E should have been \E:

$PARTIALCAPS = "\UThis half will/E become capital!";

I think it will not be worth it for me to learn enough Perl to do even the
simple things I may want to do. I should probably just hire an expert or
use some canned scripts and web apps, and stick with what I know.

Paul
 
J

Jürgen Exner

Paul E. Schoen said:
I am trying to understand scalar variables, and I found the following:
http://www.tutorialspoint.com/perl/perl_scalars.htm

Here is an excerpt:

#!/usr/bin/perl

$number = "5";
$exponent = "2 ** 8";
$string = "Hello, PERL!";
$float = 12.39;

# We can also assign a scalar an empty (undefined) value:
$nothing = undef;

# Printing all the above values
print "$number\n";
print "$exponent\n";
print "$string\n";
print "$float\n";
print "There is nothing: $nothing\n";

This will give following result
5
2 ** 8
Hello, PERL!
12.39
There is nothing:

My question is whether $number, $exponent, and $float are actually numbers
or character strings, particularly those that are enclosed in quotes.

First two are strings (exactly because they are enclosed in quotes),
$float is a number.

BUT(!!!): in Perl any string also has a numerical value and any number
also has a string value (and a boolean value, too).
Thus,
what would be the result of:

$mynum = $number * $float;

Perl recognizes that $number, although a string, is used as a number and
therefore takes its numerical value, which happens to be 5.

If you had
$mynum = $exponent * $float;
then the numerical value of the string "2 ** 8" wold be 2, not 256!
print "$mynum";

This is a useless use of quotes. See "perldoc -q always":
What's wrong with always quoting "$vars"?
print $mynum;
$mynum = 2 ** 8;
print "$mynum"

Same here
And what happens if you add characters and variables in a print statement?

print "This is a number$mynum2";

You are using the variable $mynum2 instead of the variable $mynum.
If you want to print another character directly after the value of the
variable then enclose the variable name in curly brackets:
print "This is a number${mynum}2";
The information in the FAQ did not seem to address this except as follows:

my $string = '0644';
print $string + 0; # prints 644
print $string + 44; # prints 688, certainly not octal!

Totally different issue, that's about numbers with leading 0s, which
normally are interpreted as octal, but not so when explicitely marked as
strings by enclosing them in quotes.
But what happens if you use the following:

$number = "0123";

Numerical value is 123.
$number = "A123";

Numerical value is 0 (and when used in numerical context you will also
get a warning about "argument not numerical").
$number = "one";

Numerical value is 0 (and when used in numerical context you will also
get a warning about "argument not numerical").
$number = 123;

Numerical value is 123.
$number = 123 + 4.56;

Numerical value is 127.56.
$number = "123 + 4.56";

Numerical value is 123 and when used in numerical context you will also
get a warning about "argument not numerical".
$number = "123" + "4.56";

The + operator creates numerical context, thus you are adding the
numerical values of the strings "123" and "4.56", which happen to be 123
and 4.56, thus $number contains 127.56.

jue
 
S

sln

I think I have a general aversion to languages that make assumptions about
variables, and that includes JavaScript and VB. I know enough C and Delphi
to make fairly complex Windows GUI applications that operate on a nearly
real-time basis with serial communication and data analysis, and I use a
version of C for some PIC projects, but mostly I use assembly.

I don't know shell. I found this:
http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html

I have seen awk programs. I am not familiar with the syntax.

I know a few unix commands and I have used FTP and Telnet, but that's about
it. It seems similar to MSDOS but with more powerful features (like grep).



Thanks for the warnings about on-line tutorials and other sources of
information. Even I found an error where a /E should have been \E:

$PARTIALCAPS = "\UThis half will/E become capital!";

I think it will not be worth it for me to learn enough Perl to do even the
simple things I may want to do. I should probably just hire an expert or
use some canned scripts and web apps, and stick with what I know.

Paul
Even though I have a job, I would do some side contract work for you.

-sln
 
U

Uri Guttman

PES> I think I have a general aversion to languages that make
PES> assumptions about variables, and that includes JavaScript and
PES> VB. I know enough C and Delphi to make fairly complex Windows GUI
PES> applications that operate on a nearly real-time basis with serial
PES> communication and data analysis, and I use a version of C for
PES> some PIC projects, but mostly I use assembly.

then you have an aversion to most popular languages today. c is still
used and is useful but it isn't good for dynamic data which is what web
apps typically need.

PES> I don't know shell. I found this:
PES> http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html

PES> I have seen awk programs. I am not familiar with the syntax.

PES> I know a few unix commands and I have used FTP and Telnet, but
PES> that's about it. It seems similar to MSDOS but with more powerful
PES> features (like grep).

what rock did you live under if you think unix is ftp and telnet? do you
still code on punch cards? i gave that up in 1975.

PES> I think it will not be worth it for me to learn enough Perl to do
PES> even the simple things I may want to do. I should probably just
PES> hire an expert or use some canned scripts and web apps, and stick
PES> with what I know.

your choice but don't hack it if you don't want to learn it. canned apps
are hit or miss and you won't know enough to know if they are any
good. and changing them still requires some programming skill in the
language.

uri
 
U

Uri Guttman

s> Whats your claim, apparently you know everything, sort of a jack-off
s> of all trades.
s> I work for Google as a Perl manager. Don't let your resume pass my desk!

even funnier since they use little perl. mostly python and other stuff.

and wtf is a perl manager? in any company, that would be a strange
title.

uri
 
S

sln

PES> I think I have a general aversion to languages that make
PES> assumptions about variables, and that includes JavaScript and
PES> VB. I know enough C and Delphi to make fairly complex Windows GUI
PES> applications that operate on a nearly real-time basis with serial
PES> communication and data analysis, and I use a version of C for
PES> some PIC projects, but mostly I use assembly.

then you have an aversion to most popular languages today. c is still
used and is useful but it isn't good for dynamic data which is what web
apps typically need.

WTF is a Web App, lol !!!!
There it is, throw away C++, no need for that when you got Perl.

Do they raise these pigs on Iowa corn or what?

-sln
 
C

Charlton Wilbur

PES> Sorry for the noobish questions, but I am used to C and Delphi
PES> Pascal, where I am familiar with the syntax.

It's not the syntax you're having trouble with, it's the semantics.
Perl doesn't have strongly typed variables the way the languages you
insist on comparing it with do.

A scalar holds one data value, such as a string or a number. If you
treat a scalar as if it has a number in it, Perl will do its best to
interpret that scalar as a number. If you treat a scalar as if it has a
string in it, Perl will do its best to interpret that scalar as a
string.

So yes, you can say $x = "57"; and Perl will dutifully put the string
"57" into $x. Then, when you say $y = $x + 7; Perl will interpret $x as
if it contains a number and add 7 to it. And then, when you say print
$y; -- well, Perl will convert $y to a string to print it for you.

Charlton
 
S

sln

s> Whats your claim, apparently you know everything, sort of a jack-off
s> of all trades.

s> I work for Google as a Perl manager. Don't let your resume pass my desk!

even funnier since they use little perl. mostly python and other stuff.

and wtf is a perl manager? in any company, that would be a strange
title.

uri

We at Google do %95 Perl, us managers make sure the applicants know that.

-sln
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top