Help: hash key pass to subroutine as string failed

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fenghuo
    New Member
    • Jan 2009
    • 2

    #1

    Help: hash key pass to subroutine as string failed

    I have a sub expand() to expand the path
    Code:
    sub expand($%) {
    
        my $self = shift;
        my ($string, %params) = @_;
    
        # Perform parameter checks.
        die("Mandatory parameter 'string' not defined.") unless (defined $string);
        //other handling
    }
    
    The followng call fails
     
    sub foo {
          my $files = {
            'test.in'    => 'test.out'
        };
       
        expand($_) 
            foreach ( keys( %{$files} ) );
    }
    saying the 'string' not defined.
    While the following codes work:
    sub foo {
          my $files = {
            'test.in'    => 'test.out'
        };
       
       foreach my $key ( keys %{$files} )  {
                expand (+$key); #expand ($key) also fails
       }
    }
    Could some one give me a hint why? I am newbie for Perl.
    Thanks!
    Last edited by eWish; Jan 5 '09, 02:08 PM. Reason: Please use the code tags
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    As shawn on another forum said, don't use prototypes, instead of :

    sub expand($%) {

    use a sub:

    sub expand {

    Comment

    • fenghuo
      New Member
      • Jan 2009
      • 2

      #3
      Actually I tried to remove the prototype as suggested, but still failed to pass the correct string value of the key.
      the following methods work as well:
      method 1:
      Code:
      while ( my ($key,$value)  = each (%{$files}) ){
            expand($key);
          }
      methods 2:
      Code:
      foreach my $key (keys  %{$files}  ) {
            my $s = sprintf("%s",$key);
            expand($s);
         }
      So I suspect foreach implmentation has sth. tricky.
      Any suggestion?
      Last edited by eWish; Jan 9 '09, 04:15 AM. Reason: Please use the code tags

      Comment

      • KevinADC
        Recognized Expert Specialist
        • Jan 2007
        • 4092

        #4
        See other forum

        Comment

        Working...