Perl 5 to Perl 6 - Scalars

While Perl 6 should be able to attract developers from other languages as
well, it seems it will be especially interesting for people with some background
in Perl 5. Therefore, it can be useful to have a set of articles comparing
Perl 5 and Perl 6.

In this article, we are going to look at the scalars variables,
and some of the functions dealing with them.

Note! This site is about Perl 6.
If you are looking for a solution for the current production version of Perl 5, please check out
the Perl 5 tutorial.

print Hello World

In Perl 5 you normally use print(), or starting from 5.10
you can use say() to print to the screen. The latter will
append a newline to whatever you had to say.

In Perl 6 they work the same.

use v6;
print "Hello World\n";
say "Hello World";

Variable declaration using "my"

In Perl 6 you almost always need to declare your variables with my.
Think as if you had always added use strict. Just as it is done by use 5.012;

There are exceptions, such as one-liners and certain constructs
that auto-declare the scoped variables for you.

Length of a string

In Perl 6 there is no length() function.
Instead, there is a function called chars(), that will return the number of characters.

use v6;
my $a = "This is a string";
say chars $a; # 16

chomp

In Perl 5 there is a chomp() function to remove a trailing newline
after reading a line from the standard input or from a file.

In Perl 6 this function will be almost never used as reading from
the standard input or from files will automatically chomp
off the newlines. In any case, in Perl 6 chomp behaves differently
as it returns the chomped string and does NOT change the original
string.

defined

The defined() function is the same in Perl 6 as in Perl 5,
checking if a scalar value has any value different from undef.
Except that in Perl 6 there are several different values which fall in this
category.

String concatenation using ~

In Perl 5 dot . is used for string concatenation. I think it is a lot
less used than one would think as in many cases we use string interpolation.
Maybe one of the most frequent use-cases is actually the short-cut string
concatenation.

In Perl 6 the string concatenation is done using the tilde ~ operator.
IMHO it will be even less used than in Perl 5, as the variable
and code interpolation in Perl 6 is much stronger. Anyway here is
the example:

use v6;
my $str = "Foo" ~ "Bar";
$str.say; # FooBar

I think the only place where it will be used a lot is the short-cut
version that looks like this ~=