Hi Monks!

I've noticed that my subroutine behaves differently depending on if I call it with an "&" character or not. I'm running the script on Ubuntu with Perl v5.26.1.

I have a list with duplicated entries and a subroutine that returns the unique entries from that list. If I assign the result of my subroutine to another list and then print that list, it doesn't matter if the subroutine is called with a preceding "&" character or not...

However, if I use the result of the subroutine directly in a for loop, the subroutine works fine if called with an "&" character but doesn't do it's job if it's absent!

Any thoughts; is this a feature or a fault??

#!/usr/bin/perl use strict; use warnings; my @list = qw (a a b b c c d d); print "\nAssigning list:\n"; for my $i (0 .. 1) { my @unique = ($i)? removeDuplicates (@list): &removeDuplicates +(@list); my $ampersand = ($i)? "": "&"; print $ampersand, $_, "\n" for (sort @unique); print "=\n"; } print "\nUsing in for loop:\n"; for my $i (0 .. 1) { if ($i) { for my $character (sort removeDuplicates (@list)) { print $character, "\n"; } } else { for my $character (sort &removeDuplicates (@list)) { print "&", $character, "\n"; } } print "=\n"; } sub removeDuplicates { my %hash; @hash{@_} = 1; return keys %hash; }

Running the above script gives me the following output:

user@host:~/scripts/test$ ./unique.pl Assigning list: &a &b &c &d = a b c d = Using in for loop: &a &b &c &d = a a b b c c d d = user@host:~/scripts/test$

Many thanks in advance!


In reply to Ampersand changes behavior of subroutine by w8lle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.