Loading ...
Sorry, an error occurred while loading the content.

about ref

Expand Messages
  • hellotexi
    $str = [11, 22, 33, 44]; print $$str[0] . n ; print @$str[0] . n ; 11 11 @$str[0] works? why?
    Message 1 of 2 , Jun 16, 2012
    • 0 Attachment
      $str = [11, 22, 33, 44];
      print "$$str[0]" . "\n";
      print "@$str[0]" . "\n";


      11
      11


      @$str[0] works? why?
    • Shlomi Fish
      Hi hellotexi, On Sun, 17 Jun 2012 01:28:06 -0000 ... Well, first of all, note that you should not call a scalar variable that holds an array reference str
      Message 2 of 2 , Jun 16, 2012
      • 0 Attachment
        Hi hellotexi,

        On Sun, 17 Jun 2012 01:28:06 -0000
        "hellotexi" <hellotexi@...> wrote:

        > $str = [11, 22, 33, 44];
        > print "$$str[0]" . "\n";
        > print "@$str[0]" . "\n";
        >
        >
        > 11
        > 11
        >
        >
        > @$str[0] works? why?

        Well, first of all, note that you should not call a scalar variable that holds
        an array reference "str" which is short for "string", and would be misleading
        regarding its contents. Moreover, you should use "use strict;" and "use
        warnings;" and declare such variables using "my".

        The reason why @$array_ref[0] works in this case, is because it is a way of
        writing the single-element array reference slice @{$array_ref}[0]. So you can
        also do something like:

        [CODE]

        #!/usr/bin/perl

        use strict;
        use warnings;

        my $array_ref = [11, 22, 33, 44];

        print "The slice is <<", join(",", @$array_ref[0, 2]), ">>\n";

        [/CODE]

        Or do @{$array_ref}[@indexes_array] or @$array_ref[@indexes_array] or whatever.

        Note that $$array_ref[0] can easily be confused with
        (${$array_ref})->[0], and is thus better written as $array_ref->[0] .

        For more information, see:

        * http://perl-begin.org/topics/references/

        Finally, note that you may find this list -
        http://lists.perl.org/list/beginners.html - to be a better resource for
        asking Perl questions than perl-beginner@yahoogroups.com , as it is more active,
        more populated and has a more official status. For more quality resources for
        getting help with Perl see:

        http://perl-begin.org/resources/#get_help

        Regards,

        Shlomi Fish

        --
        -----------------------------------------------------------------
        Shlomi Fish http://www.shlomifish.org/
        Optimising Code for Speed - http://shlom.in/optimise

        <rindolf> “be here or be not here — there is no maybe.”

        Please reply to list if it's a mailing list post - http://shlom.in/reply .
      Your message has been successfully submitted and would be delivered to recipients shortly.