in reply to What does $, = " " do in this code?

Hi alwynpan,

The special variable $, controls what print outputs between its arguments. See also $" and $\.

local $" = "a"; # list separator local $, = "c"; # output field separator local $\ = "l"; # output record separator my @x = ('F','O'); print @x, "@x", "x"; # prints "FcOcFaOcxl"

So $" controls what is inserted between elements when the array @x is interpolated into a string. Normally, it'd turn out to be "F O", but since we've redefined $", we get "FaO".

Next, $, controls what gets output between the arguments of print. Since the argument list is "flattened" and the elements of the array @x each become an argument to the function, the above is as if we had written print "F", "O", "FaO", "x" (this is a little bit of a simplification but good enough in this example). So the value of $, is inserted in between every argument.

Lastly, $\ is simply what print outputs at the end of the argument list. It can be useful to set it to something like "\n", but note that this affects every print statement, which is why doing so is not always a good idea in larger programs. That's also why I've used local above, because that'll limit the effect of the assignment to the current dynamic scope only.

As you can see variable names can be special characters, but Perl already uses a lot of them for special meanings, so you shouldn't try and make your own! Just use the ones Perl provides, when you need to. See perlvar. Update: Also, shmem makes an excellent point!

By the way, the code you posted shows some fairly advanced techniques, I would not recommend it as something to study for your "first day"!

Hope this helps,
-- Hauke D

Replies are listed 'Best First'.
Re^2: What does $, = " " do in this code?
by Laurent_R (Canon) on Oct 31, 2016 at 12:43 UTC
    By the way, the code you posted shows some fairly advanced techniques, I would not recommend it as something to study for your "first day"!
    I could not agree more (++), that was exactly what I was going to say if you hadn't.
Re^2: What does $, = " " do in this code?
by alwynpan (Acolyte) on Nov 01, 2016 at 03:04 UTC
    Thank you so much for your detailed explanation. Cheers.