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

Re: [PBML] Re: Creating a Variable Name ???

Expand Messages
  • Jean-Sebastien Guay
    Only the second example will give you the result you want (print onetwothree ). Here is a version that will work with use strict; Note that when using strict,
    Message 1 of 1 , Jul 31, 2003
    • 0 Attachment
      Only the second example will give you the result you want (print "onetwothree"). Here is a version that will work with use strict;

      Note that when using strict, you need to declare your variables with 'my'. That's one thing that makes use strict less error-prone, because it prevents you from making typos (as in the case of using $var[$count] instead of $x[$count], which would have popped up an error "Global symbol "@var" requires explicit package name at two.pl line 9.")

      #!/usr/bin/perl
      use strict;

      my @x = ("one", "two", "three");
      my $total = @x;

      my $varx = '';
      for (my $count = 0; $count < $total; $count++) {
      $varx .= $var[$count];
      }

      print "$varx\n";

      What I would do is put the values in a hash, and then use regexes to substitute them in a string. For example:

      #!/usr/bin/perl
      use strict;

      my %variables = (
      var1 => 'one',
      var2 => 'two',
      var3 => 'three'
      );

      my $statement = 'I have $var1 rabbit and $var3 houses and $var2 hats';
      foreach my $key (keys %variables) {
      $statement =~ s/\$${key}/$variables{$key}/g;
      }

      print "$statement\n";

      Of course, that will not work if you have one variable named 'var1' and another named 'var12' for example. Unless you sort the keys in reverse order before replacing them.

      Anyways...

      J-S



      ----- Original Message -----
      From: alex2100k
      To: perl-beginner@yahoogroups.com
      Sent: Thursday, July 31, 2003 2:39 PM
      Subject: [PBML] Re: Creating a Variable Name ???


      sorry, still can't get a result, does these work on your system?
      and taking the use strict advice has resulted in 'execution aborted
      due to compilation erros'

      any ideas?

      thanks,

      Alex.


      #!/usr/bin/perl

      $var1 = "one";
      $var2 = "two";
      $var3 = "three";

      $total = 3;

      for ($count=1; $count<=$total;$count++) {
      $varx = ("\$var$count");
      print("\n$varx\n");
      }

      OR


      #!/usr/bin/perl

      #use strict;

      @x = ("one","two","three");
      $total = @x;

      for ($count=1; $count<=$total;$count++) {
      $varx = $x[$count-1];
      print("$x");
      }


      Yahoo! Groups Sponsor
      ADVERTISEMENT




      Unsubscribing info is here: http://help.yahoo.com/help/us/groups/groups-32.html

      Your use of Yahoo! Groups is subject to the Yahoo! Terms of Service.


      [Non-text portions of this message have been removed]
    Your message has been successfully submitted and would be delivered to recipients shortly.