Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

use strict; my $row1 = '10'; my $val = 1; my $row = ${"row".$val}; print "$row\n";
I am getting below error
Can't use string ("row1") as a SCALAR ref while "strict refs" in use at test.pl line 4

Replies are listed 'Best First'.
Re: Can't use string
by Joost (Canon) on Jan 31, 2008 at 20:59 UTC
Re: Can't use string
by Fletch (Bishop) on Jan 31, 2008 at 20:56 UTC

    Yes, because you've used strict and you're trying to use a symbolic reference. That's kind of the point, it won't let you do that. Perhaps you should re-read the docs and figure out what you really want to do.

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      This is not helpful. "Hi, your program doesn't work. Read the manual."

      Looks to me like s/he's trying to dynamically generate variable names, which is usually when a person should be thinking hash or array.
Re: Can't use string
by ikegami (Patriarch) on Jan 31, 2008 at 21:55 UTC
    It sounds like you want an array.
    use strict; my @rows; $rows[1] = 10; my $val = 1; my $row = $rows[$val]; print("$row\n");

    If you're indexes are sparsed or strings, a hash would be more appropriate.

    use strict; my %rows; $rows{1} = 10; my $val = 1; my $row = $rows{$val}; print("$row\n");
      Technically the OP is using a hash. A realy ugly hackish hash.

        Are you referring to the fact that a symbol table is a sort of hash and that the code results in a lookup of the package's symbol table?

        If you start calling that a hash lookup, you must also call $_ in print("$_\n") a hash lookup — it's the same op — and the term becomes useless.

        No, the OP *isn't* using a hash.

Re: Can't use string
by rir (Vicar) on Jan 31, 2008 at 22:00 UTC
    use diagnostics can be helpful when diagnostic messages seem cryptic.

    Be well,
    rir

      I didn't know it worked for strict errors (or any other errors), so I tried it out. Turns out the diagnostic is even more cryptic than the original message, and misleading in mentioning references in what it usually a need to use a hash or array.

      >perl -e"use diagnostics; use strict; print ${'x'}" Can't use string ("x") as a SCALAR ref while "strict refs" in use at - +e line 1 (#1) (F) Only hard references are allowed by "strict refs". Symbolic references are disallowed. See perlref. Uncaught exception from user code: Can't use string ("x") as a SCALAR ref while "strict refs" in +use at -e line 1. at -e line 1
Re: Can't use string
by stiller (Friar) on Feb 01, 2008 at 12:20 UTC
    Others have pointed to reasons why you get the error message. Let me try to guess what you want instead:
    use strict; use warnings; my %value_for; $value_for{'row10'} = 1; # # later... my $key = 'row' . 10; print $value_for{$key};
    If you want a hash, you have to give it a name, unless you make it an anonymus hash of course.