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

Problem:

I have various files named *.language which contain hashes like: $LANGUAGE{content_index_misc_this} = qq~blah~; I need to convert any such items to $LANGUAGE{CONTENT_INDEX}{MISC}{THIS} = qq~blah~; The CONTENT_INDEX part is parsed from the filename, eg content_index.language. The rest needs to be converted to upper case and '_' switched for '}{'. The files are not structured, the hashes could be anywhere with none or many on each line.

I have been given this code (thanks), however, it presumes there is only two hashes to create after the content_index (misc, this) and there could be several. Also, the content_index part will change depending on the file being parsed.

#!c:\perl\bin\perl.exe $c="\$LANGUAGE{content_index_misc_this} = qq~blah~;"; $c =~ s/(\{)(.+)(\})/$1\ U$2\E$3/g; $c =~ s/_/\}\{/g; $c =~ s/(content)\}\{( index)/$1_$2/i; print $c, "\n";'

Replies are listed 'Best First'.
Re: Perl Parsing Pedantics
by Transient (Hermit) on Aug 19, 2005 at 14:15 UTC
    I stumbled a bit around traversing the hash, but hopefully this helps.
    #!/usr/bin/perl use File::Basename; use Data::Dumper; my %LANGUAGE; foreach my $language_file ( <*.language> ) { my $basename = basename($language_file, qw( .language )); my $uc_basename = uc( $basename ); open( FILE, $language_file ) or die "Unable to open $language_file!\ +n$!\n"; $LANGUAGE{$uc_basename} = {}; while ( <FILE> ) { chomp; my $hash = $LANGUAGE{$uc_basename}; if ( /\$LANGUAGE{$uc_basename([^}]*)}\s*=\s*(.*)$/i ) { my $keyword = $1; my $value = $2; if ( $keyword ) { my @sub_hashes = split(/_/, $keyword); # shift the first one off because it will be empty; shift @sub_hashes; foreach ( @sub_hashes ) { $hash->{$_} = {} unless exists $hash->{$_}; $hash = $hash->{$_}; } } $hash->{'value'} = $value; } } close( FILE ) or die "Oh no! COuldn't close $language_file!\n$!\n"; } print Dumper( \%LANGUAGE );
Re: Perl Parsing Pedantics (Data::Diver)
by tye (Sage) on Aug 19, 2005 at 23:46 UTC

    That's what I created Data::Diver for.

    Let me know if you have any questions / problems -- I won't give example code here, in part as a test of the documentation. (:

    - tye        

Re: Perl Parsing Pedantics
by aukjan (Friar) on Aug 19, 2005 at 13:46 UTC
    Please only use code tags arround actual code and not the whole text... And what is your question?

    Go Fish!

      At least it's readable; granted he needs to learn how to format things correctly, but let's give him a little bit of a break.

      -Scott