Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: Hash of Array references

by choroba (Bishop)
on Aug 04, 2014 at 14:18 UTC ( #1096129=note: print w/replies, xml ) Need Help??

in reply to Hash of Array references

I'd create a hash where the number is the key and each value is an array (reference) than contains the user and the comments.
#!/usr/bin/perl use warnings; use strict; #Header printf "%-12s %-10s %s\n", qw(Number User Comments); my $result =`cmd to get the result`; my %users; while ($result =~ /number (\d+).*user:\s*(\S+)\s*#\s*(.*)/g) { my ($number, $user, $comment) = ($1, $2, $3); printf "%-12s %-10s %s\n", $number, $user, $comment; $users{$number} = [ $user, $comment ]; } print 'Select a number: '; my $input = <STDIN>; chomp $input; if (exists $users{$input}) { print "@{ $users{$input} }\n"; } else { print "Unknown number.\n"; }

Update: Fixed typos in the code after testing it.

لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Replies are listed 'Best First'.
Re^2: Hash of Array references
by sravs448 (Acolyte) on Aug 04, 2014 at 15:02 UTC

    It worked great. But how can I access the respective $user and $comments independetly?

    print 'Select a number: '; my $input = <STDIN>; chomp $input; if (exists $users{$input}) { print "Number entered is : $users{$input} \n"; print "User for the number $users{$input} is : \n"; print "Comments for the number $users{input} is : \n"; } else { print "Unknown number.\n"; }

    Something like this in the output

    Number entered is : 12345678 User for number 123456789 is : Sam Comments for the number 123456789 is : Changed "abc" in the file

        Thanks a lot..I just got it.. But is there any way to store the number as well in the array?. I need to provide user with 2 options.Either display all the details or display details of any specific number

        print "PRESS 1 to display a single number details \n 2 to display all the numbers and details\n or any other key to EXIT :"; chomp($option2=<STDIN>); if ($option2 =="1") { print "Enter the number:"; my $input = <STDIN>; chomp $input; if (exists $users{$input}) { print "@{ $users{$input} }\n"; print "$users{$input}[0] \n"; print "$users{$input}[1] \n"; } else { print "Unknown number.\n"; } } elsif ($option2 == "2") { # display all the numbers and their respective user and co +mments.something like the below one # The details for number 1234567 are user : sam, comments: +changed abc in a file. The details for number 343434 are user:john, comments: d +eleted abc in a file } else { print "Invalid option\n"; }

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1096129]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2018-02-24 22:16 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (311 votes). Check out past polls.