Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5837969
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T11:25:04+00:00 2026-05-22T11:25:04+00:00

I have written Perl code to actually create a Trie datastructure given a set

  • 0

I have written Perl code to actually create a Trie datastructure given a set of words in an array. Now I have problems traversing and printing the words.

Also pasted the Dumper output of the Datastructure created.

The final set of words after traversal doesn’t seem to be right since the traversal logic is certainly missing something. But the trie creation is fine and works fast. Can someone help me here?

The top level of the trie is a hash

  1. Each hash item has a key which is a
    letter and each hash points to a
    array ref.

  2. Array ref again contains a
    list of hashes and each hash item is
    same as 1

If you see the first word in the output. It comes up as archtopriumwe.

We should get arc,arch,atop,atrium,awe

CODE

use Data::Dumper;
my %mainhash;

## Subroutine
sub storeword   {
    my $type = shift;
    my $fc = shift;
    my $word = shift;
    return if ((not defined $word) or (length($word) == 0));    
    my @letters =  split (//,$word);
    my $len = scalar(@letters) - 1;
    my ($arr_ref,$pass_ref,$flag ,$i,$hashitem,$newitem);
    $pass_ref = $hashitem = $new_item = undef;
    $arr_ref = $type;
    $setstop = 1 if (length($word) == 1);   
    $flag =0;
    for($i = 0;$i {$letters[0]}) {
            $flag =1;
            $pass_ref = $hashitem->{$letters[0]};
            last;
        }
    }
    if ($flag == 0) {
        $newitem->{$letters[0]} = [];   
        push(@$arr_ref,$newitem);
        $pass_ref = $newitem->{$letters[0]};
    }

    storeword($pass_ref,$letters[0],join ('',@letters[ 1..$len]));
}

## Subroutine
sub process {
    my ($prefix,$trie) = @_;
    for my $letter (sort keys %$trie) {
        if ( @{ $trie->{$letter} } ) {
            for my $branch (@{ $trie->{$letter} }) {
                process("$prefix$letter", $branch);
            }
        }
        else {
            print "$prefix$letter\n";
        }
    }
}

##main

##list of words
my @wd =  qw (arc atop awe blob boil fame tub arch atrium);

##inserting each word into the datastructure
foreach my $w (@wd) {
    my @letters = split (//,$w);
    my $len = scalar(@letters) - 1;
    if (not exists $mainhash{$letters[0]})  {
        $mainhash{$letters[0]} = [];
    }
    storeword($mainhash{$letters[0]},$letters[0],join ('',@letters[ 1..$len])); 
}
    print Dumper(%mainhash);
        ## Trying to print each word from trie.
    print("\n List of words\n");    
    process('',\%mainhash);


Output:

$VAR1 = 'a';
$VAR2 = [
          {
            'r' => [
                     {
                       'c' => [
                                {
                                  'h' => []
                                }
                              ]
                     }
                   ]
          },
          {
            't' => [
                     {
                       'o' => [
                                {
                                  'p' => []
                                }
                              ]
                     },
                     {
                       'r' => [
                                {
                                  'i' => [
                                           {
                                             'u' => [
                                                      {
                                                        'm' => []
                                                      }
                                                    ]
                                           }
                                         ]
                                }
                              ]
                     }
                   ]
          },
          {
            'w' => [
                     {
                       'e' => []
                     }
                   ]
          }
        ];
$VAR3 = 'b';
$VAR4 = [
          {
            'l' => [
                     {
                       'o' => [
                                {
                                  'b' => []
                                }
                              ]
                     }
                   ]
          },
          {
            'o' => [
                     {
                       'i' => [
                                {
                                  'l' => []
                                }
                              ]
                     }
                   ]
          }
        ];
$VAR5 = 'f';
$VAR6 = [
          {
            'a' => [
                     {
                       'm' => [
                                {
                                  'e' => []
                                }
                              ]
                     }
                   ]
          }
        ];
$VAR7 = 't';
$VAR8 = [
          {
            'u' => [
                     {
                       'b' => []
                     }
                   ]
          }
        ];

List of words
archtopriumwe
bloboil
fame
tub

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T11:25:05+00:00Added an answer on May 22, 2026 at 11:25 am

    Do you see that your code as is is only printing each letter in the datastructure once, instead of once per word it is in? And only printing a newline once for each top-level letter in the tree, not one per word?

    To fix this, you need to pass some more context into your recursive sub. Something like this:

    sub process {
        my ($prefix, $trie) = @_;
        for my $letter (sort keys %$trie) {
            if ( @{ $trie->{$letter} } ) {
                for my $branch (@{ $trie->{$letter} }) {
                    process("$prefix$letter", $branch);
                }
            }
            else {
                print "$prefix$letter\n";
            }
        }
    }
    
    print("\n List of words\n");
    process('', \%mainhash);
    

    This doesn’t print arc, because you provide no way to tell in your datastructure that arc is a word but e.g. boi is not. The value for each letter needs to provide two things: a boolean indicator that this is the end of a word, and a list of possible following letters and their sub-trie.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have written a small Perl script and now I would like to create
I have written a Perl script to read the configuration file and create CGI
I want another developer to run a Perl script I have written. The script
I have written some code in my VB.NET application to send an HTML e-mail
I have a script that's written in perl, and executed as CGI. It works
I'm attempting to move a web app we have (written in Perl) from an
I have written a Perl XS wrapper for a C library consisting of about
I have written a small script in Perl which I am executing on Windows
I have written an AIR Application that downloads videos and documents from a server.
I have written a site in Prototype but want to switch to jQuery. Any

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.