Beginner Perl help Please


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Beginner Perl help Please
# 1  
Old 04-08-2011
Beginner Perl help Please

Hi I am trying to generate random names using perl script.

First let me post my code

Code:
#!/usr/bin/perl 
my $name; 
my @charset = (('A'..'Z'), ('a'..'z')); 
my $range = $#charset + 1; 
print "Enter the limit\n"; 
$lim = <STDIN>; 
 
until ($lim == 0){ 
for (1..8) { 
   $name .= $charset[int(rand($range))]; 
} 
print "$name\n"; 
$lim = $lim - 1; 
}


So this code first asks the number of names that I want to generate after that it generates the number of names.

My problem is I dont want it to generate the way it is doing now.
here is the output if i give limit as 6

PeTFDyCo
PeTFDyCotpeZftCG
PeTFDyCotpeZftCGCztEldLf
PeTFDyCotpeZftCGCztEldLfdULnsqvx
PeTFDyCotpeZftCGCztEldLfdULnsqvxhYNMboqM
PeTFDyCotpeZftCGCztEldLfdULnsqvxhYNMboqMXIDiwnOw

Here it generates 6 names, but I have two issues here

1) I dont want the previous name to be appended(prefix) to the next name

2) I want all the names to be of same length

Please help me. Thank you.
# 2  
Old 04-08-2011
You don't nullify the name temp variable after generation.

However you should also make the code as re-usable as possible.

Here's a quick example.
Code:
#!/usr/bin/perl 

# Always do this as it will make life easier inb the long run
use strict;
use warnings;

print "Enter the number of names to generate: ";
my $count = <STDIN>;
print "Enter the number characters per name: ";
my $lim = <STDIN>;

# if you want to use a pre-set size call gen_names($count,8)
print_names(gen_names($count, $lim));

sub gen_names{
    my($count, $lim) = @_;
    my @names; # The array we redturn
    for (1..$count){
        my $name; # set name variable to empty
        for (1..$lim) {
            $name .= rand_char();
        }
        push @names, ucfirst($name);
    }
    return @names;
}

sub rand_char{
    my @charset = ('a'..'z');
    return $charset[int(rand(@charset))];
}

#Split the generation and presentation logic so you can reuse the code 
sub print_names{
    my @names = @_;
    for my $name (@names){
        print "$name\n";
    }
}

The names are now in title case and should you need to generate random characters or names again you have pre-written functions.

Last edited by Skrynesaver; 04-08-2011 at 07:27 AM.. Reason: neatened the code
This User Gave Thanks to Skrynesaver For This Post:
# 3  
Old 04-14-2011
Ok, Thanks for the help. I appreciate it.
Now I have generated 4 types of names similarly like the above example.
I am able to insert 1st generated data into the database. But how will I insert several fields. I am generating 4 different types of random names ( fname, lname, userid & email id)

/here is the code i am trying with
Code:
#!c:\perl\bin\per.exe

use strict;
use warnings;
use DBI;
my $username = 'root';
#my $password = 'ajitteli';
my $database = 'register';
my $server = 'localhost';

my ($fname, $lname, $userid, $email, $lim, $count, @fnames, @lnames, @userids, @emails);
my @charset = (('A'..'Z'), ('a'..'z'));
my $edomain = '@domain.com';
#my $range = $#charset +1; # Note in a scalar context an array returns the number of elements
print "Enter the number of names to generate: ";
chomp($count = <STDIN>);
#print "Enter the number characters per name: ";
#chomp($lim = <STDIN>);
$lim = 6;
for (1..$count){
    $fname="";
    for (1..$lim) {

        $fname .= $charset[int(rand(@charset))];
    }
    push @fnames, $fname;
}
for (1..$count){
    $lname="";
    for (1..$lim) {

        $lname .= $charset[int(rand(@charset))];
    }
    push @lnames, $lname;
}
 for (1..$count){
    $userid="";
    for (1..$lim) {

        $userid .= $charset[int(rand(@charset))];
    }
    push @userids, $userid;
}

for (1..$count){
    $email="";
    for (1..$lim) {

        $email .= $charset[int(rand(@charset))];
        $email .= $edomain;
    }
    push @emails, $email;
}

my $dbh = DBI->connect("DBI:mysql:$database;host=$server", $username)
|| die "Could not connect to database: $DBI::errstr";

#Split the generation and presentation logic so you can reuse the code
for my $fname (@fnames) && for my $lname (@lnames) && for my $userid (@userids) && for my $email (@emails)){


my $dataenter = "insert into login (Firstname, Lastname, Userid, Emailid) values ('$fname', '$lname', '$userid', '$email')";

my $sth = $dbh->prepare($dataenter);
$sth->execute
or die "SQL Error: $DBI::errstr\n";


# my $insert_reg = $dbh->(q{insert into Registration (Student_Name) values (?)}) or die $dbh->errstr;
}
$dbh->disconnect();
print "The database table is updated successfully\n";


I am getting the following error when I execute.
Code:
"my" variable $lname masks earlier declaration in same scope at entries.pl line
63.
"my" variable @lnames masks earlier declaration in same scope at entries.pl line
 63.
"my" variable $userid masks earlier declaration in same scope at entries.pl line
 63.
"my" variable @userids masks earlier declaration in same scope at entries.pl lin
e 63.
"my" variable $email masks earlier declaration in same scope at entries.pl line
63.
"my" variable @emails masks earlier declaration in same scope at entries.pl line
 63.
syntax error at entries.pl line 63, near ") &&"
syntax error at entries.pl line 74, near "}"
Execution of entries.pl aborted due to compilation errors.

---------- Post updated at 10:25 AM ---------- Previous update was at 10:00 AM ----------

Never mind I got it rite.
I removed all the for loops and added only 1 for loop at the beginning .
Code:
for (1 to count) 

generate 1 random fname 
generate 1 random lname 
generate 1 random userid 
generate 1 random email

connect to database
insert to database 
 disconnect; 
}

This is working fine.

Please let me know if you have any better logic
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Red Hat

Help me please i am beginner

i have windows 8 host on Dell Laptop vmware 9 redhat 7.2 iso downloaded through redhat official site after installation on vm it only boots into text dont show graphics Please guide:( (1 Reply)
Discussion started by: hananabbas
1 Replies

2. Shell Programming and Scripting

Beginner Need Help on perl input

Hi, I am beginner perl input I just want to know if I want to make a program that let user input a function such as input " < value " List all files that are less than value The current directory is used. eg input " < 5" list all file that less than 5 in current directory until user input "quit" ... (4 Replies)
Discussion started by: guidely
4 Replies

3. Shell Programming and Scripting

Unix Beginner needs help

how do i implement a script that asks user to input a word. it should ask for input a word continuously until the word is longer than 5 characters then stop. this is what i have so far #!/bin/bash read -p "enter word" word1 while ; do echo "continue" done (4 Replies)
Discussion started by: marcusstar10
4 Replies

4. Shell Programming and Scripting

Beginner looking for help

Hello, I am trying to write a script that reads names from a file called input, removes names if they have the same letter next to each other and prints the others. e.g. Colin & John would be printed Garry & Lynn would be removed My thinking is that I read in each name and... (3 Replies)
Discussion started by: colinireland
3 Replies

5. UNIX for Dummies Questions & Answers

Beginner - What Should I Do First?

Hi people.... I have just started to learn unix.I want to know which version of Unix to install plus how to install it.I need to practise and make myself aware of how unix works.My thread is from an educational point of view.Also please feel free to give your suggestions as I am... (3 Replies)
Discussion started by: amit.kanade1983
3 Replies

6. Shell Programming and Scripting

Beginner Help

I need to write a script to test a nsort c program. I have written 8 .txt files with different cases. Also 8 .txt files with expected outcome. The shell I have written always "test pass" for the first case but always "fail" for the rest... Here is a portion of my code (as I still don't know how to... (5 Replies)
Discussion started by: thibodeau
5 Replies

7. UNIX for Dummies Questions & Answers

Beginner Help

hi guys, i have a DEl xps laptop cor 2 duo 2.2 i have vista installed on it i want to install a dual Boot UNIX on it.. can some one guide me ...cause i m tottaly new to UNIX i want to install unix on that laptop along with Vista.... thx any help would be deeply appreciated (sorry if i... (5 Replies)
Discussion started by: Farhan082
5 Replies

8. Shell Programming and Scripting

Beginner for Perl

Hi, I'm new in Perl. Can anyone recommend me any e-book which is good for beginners? Thanks. (3 Replies)
Discussion started by: raul15791
3 Replies

9. Programming

Beginner C

Anyone know where I can get started in C++ programming in unix? Any good free tutorials or websites to start at? I am okay in unix scripting but have never done c programming of any sort... What are the main advantages of using C++ ? (2 Replies)
Discussion started by: frustrated1
2 Replies

10. Shell Programming and Scripting

Please help. I am a beginner.

Alrigt, I need to write a shell script where it counts the number of folders and files and dispays "My home directory has 'x' files and 'y' directories." So, I was thinking of doing this. set x = `ls | wc` so, if I have 8 files and folders in my home directory, x is not 8. now, I was... (1 Reply)
Discussion started by: Lykathea Aflame
1 Replies
Login or Register to Ask a Question