in reply to Defining hash structure

Does the input actually contain the string "Press <space> to continue, <cr> to single step, ? for help", or is that just from your viewer program?

It looks like the input consists of fixed-width fields. Have a look at Parse::FixedLength, it may already do most of what you need. The classic approach is unpack with the A template. Otherwise, if the input contains variable-length records separated by a special character (such as tab), Text::CSV is the way to go.

Replies are listed 'Best First'.
Re^2: Defining hash structure
by mtx (Initiate) on Aug 25, 2014 at 09:13 UTC

    I changed the content and inserted a ^ delimiter.

    I have this but I don't know how to match the structure:

    use Path::Class; use Data::Dumper; my $dir = dir("C:\\temp\\"); my $file = $dir->file("hashinput.txt"); my $file_handle = $file->openr(); my %slotHash = (); while (my $line = $file_handle->getline()){ if (index($line, "Press", 0) == -1) { $delimiter = quotemeta("^"); my @values = split(/$delimiter/, $line); %slothash = (slot => @values[0] => [type => @values[1]]); } } print Dumper(%slothash);
    Really don't know much about hashes.
      Hi mtx,

      Try to write the hash this way:

      $slotHash{$values[0]} = { slotID => $values[0], description => $values[1], hwVersion => $values[2], swVersion => $values[3], uptime => $values[4], };

        Thank you all for your help, I got the desired result and didn't have to change the contents of the file, here is the code for reference

        use Path::Class; use Data::Dumper; #Input was inserted into a file... my $dir = dir("C:\\temp\\"); my $file = $dir->file("hashinput.txt"); my $file_handle = $file->openr(); my %slotHash = (); while (my $line = $file_handle->getline()){ if (index($line, "Press", 0) == -1 && index($line, "Slot", 0) +== -1) { $value0 = substr($line, 0, 2); $value1 = substr($line, 3, 17); $value2 = substr($line, 20, 15); $value3 = substr($line, 36, 17); $value4 = substr($line, 55, 17); $uptime = $value4; my $find = " days "; my $replace = ":"; $find = quotemeta $find; # escape regex metachars if prese +nt $uptime =~ s/$find/$replace/g; $delimiter = quotemeta(":"); my @uptime = split(/$delimiter/, $uptime); $totalUptime = (((@uptime[0] * 24) * 60) * 60) + ((@uptime +[1] * 60) * 60) + (@uptime[2] * 60) + @uptime[3]; $slothash{$value0} = ( {type => substr($value1,0, 3) ,slotID => $value0, des +cription => $value1,hwVersion => $value2, swVersion => $value3 ,slotI +d => $value0, upTime => $totalUptime} ); } } print Dumper(\%slothash);
        THANKS!

      If you write to a hash via %hash = ($key => $value);, it'll overwrite the contents of the hash every time. If instead you want to add data to a hash, you need to write $hash{$key} = $value;. Since your output is a hash containing more hashes, this should be very helpful to you: hashes of hashes. By the way, your last line is better written print Dumper(\%slothash);, you'll see the data structure more clearly.