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

I am coding a cgi which drops anchors to the htmlcode.
currently I have one line code for each letter of the
alphabet. I'd like to put those 26 lines in one single
loop.

As the perlbook says that:
$name="bam"; $$name=1; # Sets $bam
I tried the following:
$name=chr(97); $$name=1; # shall set $a bot doesn't

What have I to do to let that set the variables
indicated by chr()?
--
there are no silly questions
killerhippy

Replies are listed 'Best First'.
Re: scalar symbolic reference to variables
by joealba (Hermit) on May 24, 2002 at 16:26 UTC
    Is there a good reason why you're using symbolic refs?

    You can almost always use a hash in any place where symbolic refs are used -- and the hash is almost always better form. Plus in this case, a hash would resolve the problem that Joost mentions about setting the sort vars $a and $b.

    Update: I use the word "almost" just to cover myself. My real belief is that using a hash is ALWAYS the best choice, but I know someone would come up with an argument. :)

    Update 2: This will set up a hash of letters for ya, although it's not really clear from your post how you plan to use the values.

    my %letters = map {$_,1} (a..z);
Re: scalar symbolic reference to variables
by Joost (Canon) on May 24, 2002 at 16:02 UTC
    $name=chr(97); $$name=1; # shall set $a to 1 print "$$name\n"; print "$a\n";
    results in:
    1 1
    so it DOES work.

    But don't use $a and $b, they're used by sort.

    see

    perldoc -f sort perldoc perlvar

    Actually, you almost never need symbolic references at all....

    -- Joost downtime n. The period during which a system is error-free and immune from user input.
      Silly me misinterpreted the output of my testsnippet,
      so fool me for that ;)

      Thanx to all answers especially Joost warning about
      using $a !

      To tell the whole story read this:

      I am working on a cgi producing a two framed set. the
      left frame is showing a dynamically list of links,
      which should be anchored to jump to the letter you
      want by clicking on a link at the right frame.

      so here's what I experimented with:
      for $loop (1 .. $last_id) { for $count ( 97 .. 122) { $bla=chr($count); if ( ($list[1+($loop-1)*2]=~/^$bla/i) and (! $$bla) ) { $$bla="<a name=\"$bla\"></a>\n"; print $$bla; } } }
      I intend to puplish the whole code when it's finished
      an working. It is a database for managing your
      video-cds.

      --
      there are no silly questions
      killerhippy
Re: scalar symbolic reference to variables
by BUU (Prior) on May 24, 2002 at 15:59 UTC
    dunno, this:
    $x=chr(97); $$x=1; print $a;
    prints 1 for me, so dunno. But is there something wrong with using an array? or mebbe a hash.. @chars=map{chr$_}(97..123)