Monday, June 22, 2009

Perl - DBI Programming:

Handles:
Driver Handles:
The actual instantiation of driver handles happens ''under the hood'' of DBI, typically when DBI->connect() is called.
Statement Handles:

Database Handles:
Database handles are the first step towards actually doing work with the database, in that they encapsulate a single connection to a particular database.


Connecting to DB:

$dbh = DBI->connect( $data_source, $username, $password, \%attr );
The final argument, \%attr, is optional and may be omitted


Ex:

use DBI; # Load the DBI module
### Perform the connection using the Oracle driver
my $dbh = DBI->connect( "dbi:Oracle:archaeo", "username", "password" )
or die "Can't connect to Oracle database: $DBI::errstr\n";
exit;


Note:
We can have any number of Database Handles for same Database.


Disconnecting:

Since DBI handles are references to Perl objects,
Perl's own garbage collector will move in and sweep up any object trash you leave lying around.

It does that by calling the object's DESTROY method when there are no longer any references to the object held by your script, or when Perl is exiting.


Piece of Code :

### Prepare a SQL statement for execution
my $sth = $dbh->prepare( "SELECT * FROM megaliths" )
or die "Can't prepare SQL statement: ", $dbh->errstr(), "\n";

### Execute the statement in the database
$sth->execute
or die "Can't execute SQL statement: ", $sth->errstr(), "\n";

### Retrieve the returned rows of data
while ( my @row = $sth->fetchrow_array() ) {
print "Row: @row\n";
}
warn "Problem in fetchrow_array(): ", $sth->errstr(), "\n"

if $sth->err();
### Disconnect from the database
$dbh->disconnect




Fetching Columns:

while ( @row = $sth->fetchrow_array ) {
### Print out a wee message
print "Megalith site $row[0] is a $row[1]\n";
}



Quick way to Ftech & Print:

$sth = $dbh->prepare( "
SELECT name, mapref, location
FROM megaliths
" );
$sth->execute( );
$rows = $sth->dump_results( );

which would display the following results:

'Balbirnie', 'NO 285 029', 'Balbirnie Park, Markinch, Fife'
'Castlerigg', 'NY 291 236', 'Near Keswick, Cumbria, England'
'Sunhoney', 'NJ 716 058', 'Near Insch, Aberdeenshire'
'Avebury', 'SU 103 700', 'Avebury, Wiltshire, England'



Dump the formatted results to the file:

### Dump the formatted results to the file
$rows = $sth->dump_results( 80, '\n', ':', \*FILE );


do vs Prepare:




do method used with database handle..

$dhb->do(insert into ....); internally uses prepare,execute ...

### Setup the statement for repeated execution

$sth = $dbh->prepare( "INSERT INTO megaliths ( name ) VALUES ( ? )" );

### Iterate through the various bits of data...
foreach $name ( qw( Stonehenge Avebury Castlerigg Sunhoney ) ) {
### ... and insert them into the table

$sth->execute( $name );


Fetching Only 1 Row:

selectrow_array( ) and selectrow_arrayref( ) .

>> Like fetchrow_array,fetchrow_arrayref..
* Used with database Handle..


$dbh->selectrow_array( "SELECT name, mapref
FROM megaliths" ); // No need of prepare,execute..

Thursday, June 4, 2009

SQL -Quick Tutorial

Points to Remember in SQL:

**** SQL TUTORIAL ****


1. delete from employee;

Note: if you leave off the where clause, all records will be deleted!


2. Dropping the table removes the table definition as well as all of its rows.

drop table "tablename"

Example:

drop table myemployees_ts0211;


3. ALL and DISTINCT are keywords used to select either ALL (default) or the "distinct" or
unique records in your query.




4. Aggregate Functions:


Aggregate functions are used to compute against a "returned column of numeric data" from your SELECT statement.
They basically summarize the results of a particular column of selected data.

* MIN,MAX,SUM,COUNT,AVG.

Used with GROUP BY.

5. Group By Clause:


The GROUP BY clause will gather all of the rows together that contain data in the specified column(s) and
will allow aggregate functions to be performed on the one or more columns.

This can best be explained by an example:

GROUP BY clause syntax:
SELECT column1, SUM(column2) FROM "list-of-tables" GROUP BY "column-list";


select max(salary),last_name,dept from employee group by dept,last_name;


6.HAVING clause [ grabbing particular data from result of group by ]

The HAVING clause allows you to specify conditions on the rows for each group -
in other words,
which rows should be selected will be based on the conditions you specify..


Ex: SELECT dept, avg(salary)
FROM employee
GROUP BY dept
HAVING avg(salary) > 20000;


7.IN and BETWEEN Conditional Operators:[ NoT IN/NOT Between ]

* SELECT employeeid, lastname, salary
FROM employee_info
WHERE lastname IN ('Hernandez', 'Jones', 'Roberts', 'Ruiz');


* SELECT employeeid, age, lastname, salary
FROM employee_info
WHERE age BETWEEN 30 AND 40;

8.JOIN: (NORMAL JOIN==INNER JOIN)

* SELECT customer_info.firstname, customer_info.lastname, purchases.item
FROM customer_info, purchases
WHERE customer_info.customer_number = purchases.customer_number;


* SELECT customer_info.firstname, customer_info.lastname, purchases.item
FROM customer_info INNER JOIN purchases
ON customer_info.customer_number = purchases.customer_number;

9. OUTER JOIN:
[ LEFT/RIGHT ]

The second type of SQL JOIN is called SQL OUTER JOIN and it has 2 sub-types called LEFT OUTER JOIN and RIGHT OUTER JOIN.

The LEFT OUTER JOIN or simply LEFT JOIN (you can omit the OUTER keyword in most databases), selects all the rows from the first table listed after the FROM clause,
no matter if they have matches in the second table.

FULL OUTER JOIN: Return rows in LEFT and right even there is no Matches.

Use FULL JOIN in Query.

10. INSERT QUERY:


INSERT INTO Customers (FirstName, LastName, Email, DOB, Phone)
VALUES ('Peter', 'Hunt', 'peter.hunt@tgmail.net', '1/1/1974', '626 888-8888')

11.TABLE ALIAS:

SELECT Emp.Employee FROM EmployeeHours AS Emp


12. NOTE on this Query
:

When using SQL on text data, "alfred" is greater than "a" (like in a dictionary).
SELECT CompanyName, ContactName
FROM customers
WHERE CompanyName > 'g'
AND ContactName > 'g'


13. SQL Wildcards:


SQL wildcards must be used with the SQL LIKE operator.

With SQL, the following wildcards can be used:

Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist] or [!charlist] Any single character not in char


14. SQL UNION:
[ 1 Result set Followed by Second Result Set]

The SQL UNION operator combines two or more SELECT statements.
The UNION operator is used to combine the result-set of two or more SELECT statements.

Notice that each SELECT statement within the UNION must have the same number of columns.
The columns must also have similar data types.
Also, the columns in each SELECT statement must be in the same order.

15.UNION & UNION ALL:

The UNION operator selects only distinct values by default.
To allow duplicate values, use UNION ALL.


16.SQL SELECT INTO Example


Make a Backup Copy - Now we want to make an exact copy of the data in our "Persons" table.

SELECT *
INTO Persons_Backup
FROM Persons

17.IN CLAUSE Example:
We can also use the IN clause to copy the table into another database:

SELECT *
INTO Persons_Backup IN 'Backup.mdb'
FROM Persons

18.SELECT INTO
- Joined Tables

Selecting data from more than one table is also possible.

The following example creates a "Persons_Order_Backup" table contains data from the two tables "Persons" and "Orders":
SELECT Persons.LastName,Orders.OrderNo
INTO Persons_Order_Backup
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id


19.CREATE DATABASE Syntax

CREATE DATABASE database_name;

20.SQL Constraints

Constraints are used to limit the type of data that can go into a table.

Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).


* NOT NULL
* UNIQUE
* PRIMARY KEY
* FOREIGN KEY
* CHECK
* DEFAULT

21.Unique Constraint:


CREATE TABLE Persons
(
P_Id int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)


**** For More than a Column:
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

* allows dropping constraint easily than updating each column..
ALTER TABLE Persons
DROP CONSTRAINT uc_PersonID

22. PRIMARY KEY Constraint:


SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values.
A primary key column cannot contain NULL values.
Each table should have a primary key, and each table can have only one primary key.

Example:


CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

* For More than One column: CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

We can alter a table by

ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)


23. FOREIGN KEY:

The FOREIGN KEY constraint is used to prevent actions that would destroy link between tables.

The FOREIGN KEY constraint also prevents that invalid data is inserted into the foreign key column,
because it has to be one of the values contained in the table it points to.


Example:

CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:


CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)

24.SQL CHECK Constraint

The CHECK constraint is used to limit the value range that can be placed in a column.

Age varchar2(10) check(age>0)

On 2/More Columns,
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')


25.SQL DEFAULT Constraint on CREATE TABLE

The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is created:

My SQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255) DEFAULT 'Sandnes



26. CREATE INDEX Statement


The CREATE INDEX statement is used to create indexes in tables.

Indexes allow the database application to find data fast; without reading the whole table.
Indexes
An index can be created in a table to find data more quickly and efficiently.

The users cannot see the indexes, they are just used to speed up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
SQL CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name
ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name
ON table_name (column_name)


27.DROPPING INDEX:

DROP INDEX index_name ON table_name

28.The DROP DATABASE Statement


The DROP DATABASE statement is used to delete a database.
DROP DATABASE database_name

The TRUNCATE TABLE Statement

What if we only want to delete the data inside the table, and not the table itself?

Then, use the TRUNCATE TABLE statement:
TRUNCATE TABLE table_name


29. AUTO INCREMENT:



In Oracle the code is a little bit more tricky.

You will have to create an auto-increment field with the sequence object (this object generates a number sequence).

Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10

The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.

To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
INSERT INTO Persons (P_Id,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen')


30.VIEW :

In SQL,a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.
SQL CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition


31.SQL IS NULL

How do we select only the records with NULL values in the "Address" column?

We will have to use the IS NULL operator:
SELECT LastName,FirstName,Address FROM Persons
WHERE Address IS NULL

[ cant be compared with ' ' and >,<,etc ]


32. ORACLE DATATYPES:

INTEGER
This ANSI datatype will be accepted by Oracle - it is actually a synonym for NUMBER(38)

The FLOAT datatype
This ANSI datatype will be accepted by Oracle - Very similar to NUMBER it stores zero, positive, and negative floating-point numbers

The NUMBER datatype
Stores zero, positive, and negative numbers, fixed or floating-point numbers

Fixed-point NUMBER
NUMBER(p,s)
precision p = length of the number in digits
scale s = places after the decimal point, or (for negative scale values) significant places before the decimal point.

Integer NUMBER
NUMBER(p)
This is a fixed-point number with precision p and scale 0. Equivalent to NUMBER(p,0)

Floating-Point NUMBER
NUMBER
floating-point number with decimal precision 38

Confusingly the Units of measure for PRECISION vary according to the datatype.
For NUMBER data types: precision p = Number of Digits
For FLOAT data types: precision p = Binary Precision (multiply by 0.30103 to convert)

{So FLOAT = FLOAT (126) = 126 x 0.30103 = approx 37.9 digits of precision.}

Example

The value 7,456,123.89 will display as follows
NUMBER(9) 7456124
NUMBER(9,1) 7456123.9
NUMBER(*,1) 7456123.9
NUMBER(9,2) 7456123.89
NUMBER(6) [not accepted exceeds precision]
NUMBER(7,-2) 7456100
NUMBER 7456123.89
FLOAT 7456123.89
FLOAT(12) 7456000.0

Oracle stores all numeric data in variable length format.


33.SQL Scalar Functions:


SQL Scalar functions

SQL scalar functions return a single value, based on the input value.

Useful scalar functions:

* UCASE() - Converts a field to upper case
* LCASE() - Converts a field to lower case
* MID() - Extract characters from a text field
* LEN() - Returns the length of a text field
* ROUND() - Rounds a numeric field to the number of decimals specified
* NOW() - Returns the current system date and time
* FORMAT() - Formats how a field is to be displayed


34. MID:
The MID() Function

The MID() function is used to extract characters from a text field.
SQL MID() Syntax
SELECT MID(column_name,start[,length]) FROM table_name

35.The ROUND() Function

The ROUND() function is used to round a numeric field to the number of decimals specified.
SQL ROUND() Syntax
SELECT ROUND(column_name,decimals) FROM table_name


36.NOW:
SELECT ProductName, UnitPrice, Now() as PerDate FROM Products

The result-set will look like this:
ProductName UnitPrice PerDate
Jarlsberg 10.45 10/7/2008 11:25:02 AM
Mascarpone 32.56 10/7/2008 11:25:02 AM
Gorgonzola 15.67 10/7/2008 11:25:02 AM


E.g SELECT ProductName, UnitPrice, FORMAT(Now(),'YYYY-MM-DD') as PerDate
FROM Products

Thursday, May 28, 2009

Shell Scripting -III

1. Write a shell script in Linux to shift all characters in a
file forward by five characters. (Thus “a” becomes “f’”)?


cat file.txt|tr [a-z A_Z} [f-za-e F_ZA-E]



2. ODD or EvEn


echo "Enter the Number"
read a
b=`echo "$a % 2"|bc`
if [ $b -eq 0 ]
then
echo "Given Number is Even "
exit
fi
echo " Given Number is odd"


3.write a shell script that counts a number of unique word contained in the file and print them in alphabetical order line by line?


Make ' ' to '\n' then pipe to sort|uniq.

#!/bin/csh
# Here tr -s ' ' replaces all multiple ' ' with single ' '
# next pipe the above stream to replace each ' ' with '\n'
# next pipe the above stream to get a sorted list of words
# then pipe the unique words to outfile
tr -s ' ' < $1 | tr ' ' '\n' | sort | uniq > $1.out


4. how to convert a string to int???

To increment
echo enter the string
read str
str=`expr $str + 1`
echo $str


for integer
declare following in your script
typeset -i str



5.string reverse using shell scripts:




6.Shift Command in Command Line argts:

What is the use of "shift" command in passing parameters?


"shift" is useful when you need to access positional
parameters more than 9.

EX- execute a script to display 11th position parameter.

#./test.sh 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th
12th

ex:
withen the script write "shift 2" before "echo $9"to
display 11th parameter.

withen the script write "shift 3" before "echo $9"to
display 12th parameter.



7.What do u mean by $#,$* in unix programming?


$# The number of command line argument
$* All the arguments on the command lin

8. Grep,e-grep [ grep extended with Regular Expressions ]


Grep Man Page


9. How to modify the PATH variable and make it executable?


we can set PATH by using export PATH command.
ex:-
PATH=/opt/j2sdk1.4.2_04/bin:............
export PATH

and to make it executable we can set the same
in ".bash_profile".

To execute it ". .bash_profile"

2)
setenv PATH "/workingdir/"



10. Linux Shell Scripting Beginner Tutorial:



Click here

Wednesday, May 27, 2009

Google Search Tips

Google தேடல் டிப்ஸ்



மேற்கோள் குறிகள் இரண்டாக அமையட்டும்: எப்போதும் நீங்கள் தேடும் சொற்கள் அல்லது சொல் தொகுதி கொண்ட இணைய தளம் வேண்டுமென்றால் அவற்றை இரு மேற்கோள் குறிகளுக்குள் அமைக்கவும். எடுத்துக் காட்டாக women who love rosesஎன்ற சொல் தொகுதி கொண்ட தளம் தேவைப்படுகையில் மேற்கோள் குறி இல்லாமல் தேடிய போது 3,46,00,000 என்ற எண்ணிக்கையில் தளங்கள் இருப்பதாகக் காட்டியது. இவற்றில் பெரும்பாலானவை நாம் தேடும் தளங்களுக்குச் சம்பந்தமில்லாதவையாக இருக்கலாம். இதனையே ""women who love roses'' என டைப் செய்து தேடிய போது தளங்கள் 45,500 என்று காட்டப்பட்டது. மேற்கோள் குறிகளுக்குள் அமைக்கப்படுகையில் மிகச் சரியாக நாம் எந்த வரிசையில் சொற்களை அமைத்திருக்கிறோமோ அந்த வரிசையில் சொல் தொகுதிகள் இருந்தால் மட்டுமே தளங்கள் கணக்கில் எடுத்துக் கொள்ளப்பட்டு தரப்படுகின்றன.




1. சிறிய நட்சத்திரக் குறியீடு (*) : ஆங்கிலத்தில் wildcard என்று கூறப்படுவதனைக் குறிக்க சிறிய நட்சத்திரக் குறியீட்டினைப் பயன்படுத்துகிறோம். இதனை உங்கள் தேடுதல் பணியிலும் பயன்படுத்தலாம். குறிப்பிட்ட சொல்லினை அடுத்து எந்த சொல் இருந்தாலும் பரவாயில்லை என்று அமைக்க இந்த குறியீட்டினை அமைத்துத் தேடலாம். குறிப்பிட்ட சொல் தொகுதியில் ஒரே ஒரு சொல்லை மறந்துவிட்டு அதனைத் தேட முயற்சிக்கையில் இந்த வகை குறியீட்டுடனான தேடல் கை கொடுக்கிறது. எடுத்துக் காட்டாக காவிரியின் குறுக்கே உள்ள பாலம் என்பதனைக் குறிக்க "the bridge on the river cauvery'' என அமைக்கலாம். ஆனால் காவேரி என்பது மறந்துவிட்டால் the bridge on the river XXஎன அமைக்க முடியாது. அது தவறான தகவலையே தரும். இங்கே the bridge on the river * என அமைத்தால் காவேரி குறுக்கே உள்ள பாலங்கள் குறித்த தகவல் கிடைக்கும். இரண்டு சொற்கள் இருக்கலாம் என தேட விரும்பினால் "the bridge on the river ** ”என அமைக்கவும்.




2.குறிப்பிட்ட தளத்தில் மட்டும்:
இணையத்தில் ஒரு குறிப்பிட்ட தளத்தில் மட்டும் நீங்கள் தேடும் தகவல் உள்ளது. ஆனால் அது எங்கே தரப்பட்டுள்ளது என்று நினைவில் இல்லை. அந்த தளத்தில் மட்டும் தேட விரும்பினால் "site:" என்று கொடுத்துத் தேடலாம். எடுத்துக் காட்டாக தமிழ் நாடு அரசின் இணைய தளமான www.tn.nic.in என்ற இணைய தளத்தில் மட்டும் ஞிச்ததிஞுணூதூ என்ற சொல் உள்ள இடங்களைப் பார்க்க விரும்பினால் "cauvery" site:www.tn.nic.in என டைப் செய்து கொடுத்து சரியான முடிவுகளைப் பெறலாம். இதே போல ஒரு குறிப்பிட்ட தளத்தில் நீங்கள் தேடும் தகவல் இருப்பது நன்றாக உங்களுக்குத் தெரியும். எனவே இந்த தளம் இல்லாமல் மற்ற தளங்களில் தேடித் தகவல்களை அறிய வேண்டும் என்றால் ஒரு கழித்தல் () அடையாளத்தை இங்கு ண்டிtஞு: ஆப்பரேட்டருக்கு முன்னால் பயன்படுத்த வேண்டும். எடுத்துக் காட்டாக காவேரி குறித்து தமிழ்நாடு அரசு தளம் தவிர மற்ற தளங்களில் தேட வேண்டும் என்றால் "cauvery" site:www.tn.nic.in எனக் கொடுத்துத் தேடலாம்.




3. அதே பொருள் தரும் சொற்களைத் தேட: ஒரு சொல்லின் பொருள் சார்ந்து இருக்கும் மற்ற சொற்களை அறிந்து கொள்ள கூகுள் தேடலை வரையறை செய்திடலாம். இதற்கு ஆங்கிலத்தில் tilde ("~") என அழைக்கப்படும் அடையாளக் குறியைப் பயன்படுத்த வேண்டும். இதனை நாம் தேடும் சொல்லின் முன்னால் எந்த இடைவெளியும் இன்றி அமைக்க வேண்டும். எடுத்துக் காட்டாக எம்.எஸ்.வேர்ட் தொகுப்பு குறித்து விளக்கமான குறிப்புகள் தரும் தளங்களைக் காண விரும்புகிறீர்கள். இந்த குறிப்புகள் என எப்படி வேண்டுமென்றாலும் இருக்கலாம். இவற்றைப் பெறும் வழியை இந்த ஆப்பரேட்டர் தருகிறது. இங்கு "msword" ~tutorial என அமைத்தால் எம்.எஸ் வேர்ட் குறித்த basics, hints, guide, tips, tricks ஆகிய அனைத்தும் கிடைக்கும்.




4.விளக்கங்கள் பெற: ஒரு சொல்லின் விளக்கங்கள் பெற கூகுள் "define" என்ற ஆப்பரேட்டரைக் கையாள்கிறது. எந்த சொல்லுக்கு விளக்கம் வேண்டுமோ அதன் முன்னால் இதனை இணைத்துச் செயல்படுத்தினால் போதும். எடுத்துக் காட்டாக nano technology என்ற சொல் குறித்து விளக்கம் வேண்டும் என்றால் define nano technology என்று கொடுத்தால் போதும். விளக்கத்தோடு இந்த சொல் பயன்படுத்தப்பட்டுள்ள அனைத்து தளங்களும் கிடைக்க what is nano technology எனக் கொடுத்துப் பெறலாம்.

TEN TIPS FOR Strengthening Perl Knowledge-1 :

1* use vars qw($VERSION $opt_h $opt_x $opt_n $..)

>> Make global variables ,same as using "our" before Variable Names..

2*What's the difference between dynamic and lexical (static) scoping? Between local() and my()?

local($x) saves away the old value of the global variable $x and assigns a new value for the

duration of the subroutine which is visible in other functions called from that subroutine. This is

done at run-time, so is called dynamic scoping. local() always affects global variables, also

called package variables or dynamic variables.

my($x) creates a new variable that is only visible in the current subroutine. This is done at

compile-time, so it is called lexical or static scoping. my() always affects private variables, also

called lexical variables or (improperly) static(ly scoped) variables.

For instance:

sub visible {
print "var has value $var\n";
}

sub dynamic {
local $var = 'local'; # new temporary value for the still-global
visible(); # variable called $var
}

sub lexical {
my $var = 'private'; # new private variable, $var
visible(); # (invisible outside of sub scope)
}

$var = 'global';

visible(); # prints global
dynamic(); # prints local
lexical(); # prints global

Notice how at no point does the value "private" get printed. That's because $var only has that

value within the block of the lexical() function, and it is hidden from called subroutine.

In summary, local() doesn't make what you think of as private, local variables. It gives a global

variable a temporary value. my() is what you're looking for if you want private variables.

See "Private Variables via my()" in perlsub and "Temporary Values via local()" in perlsub for

excruciating details.

3*How to embed data in your Perl program



Here's a sample Perl program that demonstrates how you can include (embed) data inside of

your Perl program, right in there next to the source code.

This simple program takes the data after the special __END__ tag, and makes it available to

your Perl source code.

#!/usr/bin/perl

while ()
{
print $_;
}

__END__
George Washington
Abraham Lincoln
John F. Kennedy



4*What is true and false in Perl?



Perl is a little unusual in not having true and false boolean operators. Because of this, and my

advancing age, I can never seem to remember what equates to true and false when using Perl,

so I decided to create this page.
True/false summary

In short, the following elements in Perl will equate to "false":

* The number zero (0) means false.
* The string zero ('0') means false.
* The empty string ('') means false.

Lots of other things equate to "true", including:

* Non-zero numbers
* Non-empty strings


5.Explain the difference between "my" and "local" variable scope declarations. ?

Both of them are used to declare local variables.
The variables declared with "my" can live only within the block it was defined and cannot get its

visibility inherited functions called within that block, but one defined with "local" can live within

the block and have its visibility in the functions called within that block.

6.E-val with its own interpreter >Make it Fail to Throw Errors..


The eval function provides a very simple way of checking certain events without

affecting the overall execution of your script.

In essence the eval function just initiates a new instance of the Perl interpreter in order to

evaluate a particular string or block.

Because eval evaluates a Perl statement or block within its own interpreter we can use it in

situations that might otherwise cause the Perl interpreter to fail.


This process works because an embedded eval block reports any errors raised by a call to die

through the $@ variable. In fact any exit is reported through eval to the $@ special variable. We

can demonstrate this with a simple eval block used to test the existence of a particular module:

eval
{
require Net::FTP;
}
print Error: Module failed to load ($@) if $@;

This outputs the following:

$ perl eval.pl
Failed to load Net::FTP: Can't locate Net/LICK.pm in @INC (@INC contains:
/usr/local/lib/perl5/5.6.0/i686-linux /usr/local/lib/perl5/5.6.0
/usr/local/lib/perl5/site_perl/5.6.0/i686-linux
/usr/local/lib/perl5/site_perl/5.6.0 /usr/local/lib/perl5/site_perl .) at
eval.pl line 1.


7. How to substitute a particular string in a file containing millions of records?
perl -pi -e "s/search_string/replace_string/g" SourceFile

-P
causes your program to be run through the C preprocessor before compilation by Perl.

(Because both comments and cpp directives begin with the # character, you should avoid

starting comments with any words recognized by the C preprocessor such as ``if'', ``else'', or

``define''.)

-i

-e commandline
may be used to enter one line of program. If -e is given, Perl will not look for a filename in the

argument list. Multiple -e commands may be given to build up a multi-line script. Make sure to

use semicolons where you would in a normal program.

-T
forces ``taint'' checks to be turned on so you can test them. Ordinarily these checks are

done only when running setuid or setgid. It's a good idea to turn them on explicitly for programs

that run on behalf of someone else whom you might not necessarily trust, such as CGI programs

or any internet servers you might write in Perl

8.What's the significance of @ISA, @EXPORT @EXPORT_O...??
@ISA -> each package has its own @ISA array. this array keep track of classes it is inheriting.

ex:

package child;

@ISA ( parentclass);

@EXPORT this array stores the subroutins to be exported from a module.

@EXPORT_OK this array stores the subroutins to be exported only on request.


9.Special Variables in Perl:

Go through This Link : Special Variables in Perl



10.where do you go for perl help?




You can use the command

-> perldoc -f function name

Ex: perldoc -f print





Shell Scripting Tip:


* Example for using getopts:

getopts => getting options to correct var..


while getopts t:r: MYOPTION
do
case MYOPTION in
t) RESTAURANTTYPE=$OPTARG ;;
r) RATING=$$OPTARG ;;
\?) echo "Sorry no such option, please try again"
exit 1
;;

done

// myprog -t North -r 35 or myprog -r 35 -t North

Tutorial for using getopts...[click]

Tuesday, May 26, 2009

PERL @ glance

Perl @Quick Glance


SHELL SCRIPTING-II:


1. FILE DESCRIPTORS:

File descriptors are called file handles .
The three files opened for each command along with their corresponding file descriptors are
lStandard Input (STDIN), 0
lStandard Output (STDOUT), 1
lStandard Error (STDERR), 2

Ex:
command > file 2>&1
list > file 2>&1
Here STDOUT (file description 1) and STDERR (file descriptor 2) are redirected into the specified file.

Nohup process 2>&1& , 2=>STDERR


Command >file 2>&1
2> Output Error Msgs
1> Standard ERR

command 1> file1 2> file2
Here the STDOUT of the specified command is redirected to file1, and the STDERR (error messages) to file2.


NOTE:
n>&m
Here n and m are file descriptors (integers). If you let n=2 and m=1, you see that STDERR is redirected to
STDOUT. By redirecting STDOUT to a file, you also redirect STDERR



2. Shell Version of Cat:
#!/bin/sh
if [ $# -ge 1 ] ; then
for FILE in $@
do
exec 5<&0 < "$i"
while read LINE ; do echo $LINE ; done
exec 0<&5 5<&-
done
fi


3. Listing By Last Modifed :

start with ls -1 command again, but this time I'll use the -t (sort by last modified time) option
instead:
$ ls -1t /var/spool/mail


4. Shell function Returns Operating System..

getOSName() {
case ´uname -s´ in
*BSD)
echo bsd ;;
SunOS)
case ´uname -r´ in #version
5.*) echo solaris ;;
*) echo sunos ;;
esac
;;
Linux)
echo linux ;;
HP-UX)
echo hpux ;;
AIX)
echo aix ;;
*)
echo unknown ;;
esac
}

5. Copy Side Effects::
(Use Tar. )

Major prolem: can copy only Regular Files…… (files like file@ nt copied)
There are two other minor problems with using cp:
l Some versions of the cp command do not copy a file's owner and group. With these versions of cp,
the copied file has a different owner and group than the original.
l Some versions of cp do not copy a file's permissions correctly. With such a version of cp, the copied file might have different permissions than the original.


Using tar
By using tar you can move directories using the following procedure:
1. Make a tar file of the source directory.
2. Change to the destination directory.
3. Extract the source directory in the destination directory.


6. More n More –Magic of bin/sh:

When you ask a shell to execute the command $ date, the shell uses the system call exec to
ask the UNIX kernel to execute the command you requested.

The shell passes the name of the command that should be executed to the exec system call.
This system call reads the first two characters in a file to determine how to execute the command.


In the case of shell scripts, the first two characters are #!, indicating that the script needs to be interpreted by another program instead of executed directly.

The rest of the line is treated as the name of the interpreter to use.
Usually the interpreter is /bin/sh, but you can also specify options to the shell on this line.

Friday, May 15, 2009

பிறந்த நாள் சொல்லுங்கள்.. உங்களை பற்றிய சுவாரசிய தகவல்கள்






title='Poke My Birthday' style='text-decoration: none;
color: black;'>Poke My Birthday!


Enter

your birthday and let's surprise you!

/>
value="Day" style="color:#0000FF; background-color:#FFFFCC;
font-size:15pt; width: 50px; height: 25px; font-weight:
bold; border: 1px solid #000000;" onclick="this.value=''">

- - title="byear" value="Year" style="color:#0000FF;
background-color:#FFFFCC; font-size:15pt; width: 100px;
height: 25px; font-weight: bold; border: 1px solid
#000000;" onclick="this.value=''">



Wednesday, May 13, 2009

டெக் tricks

Latest Tech Tricks













My PERL HINTS

@array = (1, 2, 3);
print (@array, "\n");
This prints the following on your screen:
123
To get around this problem, put the array you want to print into a string:
print ("@array\n");




$scalar = @array;
($scalar) = @array;
In the first statement, the length of the list in @array is
assigned to $scalar. In the second statement, the first
element of @array is assigned to $scalar

while ($count <= @array) {

@slice = @array[1,2,3];


Although single elements of an array are referenced
using the $ character, array slices are referenced using
@:
$var = $array[0];
@subarray = @array[0,1];


The array-slice notation provides an easy way to swap elements in a list. The following
is an example:
@array[1,2] = @array[2,1];
This statement swaps the second and third elements of @array. As with the overlapping
array slices you saw earlier, the Perl interpreter copies @array[2,1] into a temporary locn.

@array = ; // each line as element..


unless (open(OUTFILE, ">outfile")) { // opposite to IF.
7: die ("cannot open output file outfile\n");
8: }


the print statement sends output to the standard output file, which means
that it sends the output to the file associated with STDOUT


print STDOUT ("Here is a line of output.\n");






***** it reads a line of input from file1 because the file variable STDIN represents file1.
Similarly, specifying > on the command file redirects the standard output file from the
screen to the specified file

myperlprog outfile









FILES:


-e exists, -r file permission, -w

$list = <>;
is called myprog and is called using the command
$ myprog file1 file2 file3
In this case, the first occurrence of the <> operator reads the first line of input from
file1. Successive occurrences of <> read more lines from file1. When file1 is exhausted,
<> reads the first line from file2, and so on. When the last file, file3, is exhausted, <>
returns an empty string, which indicates that all the input has been read.


In Perl, the <> operator actually contains a hidden reference to the array @ARGV. Here's
how it works:
1. When the Perl interpreter sees the <> for the first time, it opens the file whose
name is stored in $ARGV[0].
2. After opening the file, the Perl interpreter executes the following library
function:
shift(@ARGV);
This library function gets rid of the first element of @ARGV and moves every other
element over one. This means that element x of @ARGV becomes element x-1.
3. The <> operator then reads all of the lines of the file opened in step 1.
4. When the <> operator exhausts an input file, the Perl interpreter goes back to
step 1 and repeats the cycle again



PATTERNS:
===============


(0[1-9]|[12]\d|3[01]),

===> 0[1-9] =>01,02,03....09
|[12] => 1/2
\d =>any single digit(0..9)

RE=> 0 to 31..

Perl 5 makes life a little easier by supplying the x option. This tells the Perl interpreter
to ignore white space in a pattern unless it is preceded by a backslash.



( 0[13578] | 1[02] )\2( 0[1-9] | [12]\d|3[01] )

\2 ==> Separator.....l \2, which matches the character that separates the day, month, and year


m!/u/jqpublic/perl/prog1! ===> Gud .... instead of /\u\/j....

m can be used if / is not used pattern match....

here ! we used... we can use anything other than / wid m...







\d Any digit [0-9]
\D Anything other than a digit [^0-9]
\w Any word character [_0-9a-zA-Z]
\W Anything not a word
character
[^_0-9a-zA-Z]
\s White space [ \r\t\n\f]
\S Anything other than white
space
[^ \r\t\

g Match all possible patterns
i Ignore case
m Treat string as multiple
lines
o Only evaluate once
s Treat string as single line
x Ignore white space in
pattern


/\d{2} ([\W]) \d{2} \1 \d{2}/x

s/(\d+)/($1)/g ==> puts Paranthesis..



s/\bno\b/NO/gi => no to NO,No to NO,nO to NO.

$string =~ /abc/$var/o; ===> o --->only once.



$string = "This is a\ntwo-line string.";
$string =~ s/a.*o/one/s;
# $string now contains "This is one-line string."
If the m option is specified, ^ and $ match the beginning and end of any line.
$string = "The The first line\nThe The second line";
$string =~ s/^The//gm;


For example, the following substitution
replaces all occurrences of the words no, No, NO, and nO with NO. (Recall that the \b
escape character specifies a word boundary.)




$string =~ s/\Btwo\B/one/ s; // s----> treat as single line



Replacement Using an Expression
The e option treats the replacement string as an expression, which it evaluates before
replacing. For example, consider the following:
$string = "0abc1";
$string =~ s/[a-zA-Z]+/$& x 2/e // replacemt =>evaluated b4 replacing.





$string = "This is a\n two -lintwoe string.";
$string =~ s/\Btwo\B/That x 2/es; ==> Replaces only lintwoe ... linthatthate.
$string =~ s/\btwo\b/That x 2/es; ==>replaces only two.


if ($string =~/(\d)+\.(\d)+.(\d)+.(\d)+/ ) // IP Address :-)

[a-zA-Z][a-zA-Z0-9_.]+@[a-zA-Z]+\.com|net|org|edu // E-mail Addr.






/([\da-z]+)([:;])\1\2\1/ [] =>pattern memory \1,\2,\3... so on..





~ tr/0-9/ /s all occurences of number wid space..





/[a-z]+/i
/(?i)[a-z]+/
In both cases, the pattern matches one or more alphabetic characters; the i option
indicates that case is to be ignored when matching.
The syntax for embedded pattern options is
(?option)
where option is one of the options shown in Table 7.7.
Table 7.7. Options for embedded patterns.
Option Description
i Ignore case in pattern
m Treat pattern as multiple lines
s Treat pattern as single line
x Ignore white space in pattern




If you want to enclose a subpattern in parentheses without storing it in
memory, use the ?: extended pattern-matching feature. For example, consider this
pattern:
/(?:a|b|c)(d|e)f\1/





Perl 5 enables you to use the ?= feature to define a boundary condition that must be
matched in order for the pattern to match. For example, the following pattern matches
abc only if it is followed by def:
/abc(?=def)/



Similarly, the ?! feature defines a negative look-ahead condition, which is a boundary
condition that must not be present if the pattern is to match





@list = (1, 2, 3, 4, 5);
foreach $temp (@list) {
if ($temp == 2) {
$temp = 20;
}
}
In this loop, when $temp is equal to 2, $temp is reset to 20. Therefore, the list stored in
the array variable @list becomes (1, 20, 3, 4, 5).
Use this feature with caution, because it is not obvious that the value of @list has
changed.









Perl enables you to tell the Perl interpreter to restart an iteration of a loop using the
redo statement.
Like last and next, the syntax for the redo statement is simple:

// redo possible in for loop but not in =============>>>> do ..while loop/until LOOPs.





next LABEL;
redo LABEL;



you can define statements that are to be executed whenever the end of a
while loop or an until loop is reached. To carry out this task, specify a continue
statement after the loop.
$i = 1;
while ($i <= 10) {
print ("$i\n");
}
continue {
$i++;
}

Learn Perl by Examples

CLICK HERE

Thursday, April 2, 2009

SHELL SCRIPTING -ADVANCED TIPS

Shell Script



A shell script is a list of

commands stored in a file that the shell executes noninteractively.


Scripting TIPS





1. Listing Files with F:


ls -F Will produce output different from

ls.

Now the output for the directory is

slightly different:
bin/ hosts lib/ res.03
ch07 hw1 pub/ test_results

ch07.bak hw2 res.01 users

docs/ hw3 res.02 work/

* As you can see, some of the items now

have a / at the end: each of these items is a directory. The other
items, such as hw1, have no character

appended to them. This indicates that they are ordinary files.

* When the -F option is specified to ls, it

appends a character indicating the file type of each of the items it
lists. The exact character depends on

your version of ls
. For ordinary files, no character is

appended.

*For special files, a character such as !,

@, or # is appended to the filename



2. Listing with -1:


In a shell script it is much easier to

manipulate the output when each file is listed on a separate line.
Fortunately ls supports the -1 option to

do this. For example,
$ ls -1

3. Numbering In Viewing:


The cat command also understands

several options. One of these is the -n option, which
numbers the output lines. You can use it

as follows:
$ cat -n hosts

4. Listing Only Directories:

If you don't want the

contents of the directory listed, specify the -d option to ls. This forces ls to display

only the name of the directory, not its contents:
$ ls -d /home/ranga
/home/ranga


5. Creating Necessary Directories in Mkdir:


you can specify the

-p (p as in parent) option to the mkdir command. It creates all the
necessary directories for you. For

example
$ mkdir -p /tmp/ch04/test1
creates all the required parent directories.

6. Quick Tutorial on File Attributes:


To determine a file's type, specify the -l

option to the ls. When this option is specified, ls lists the file type
for the specified files.
For example, the command
$ ls -l /home/ranga/.profile

produces the following output:
-rwxr-xr-x 1 ranga users 2368 Jul 11 15:57

.profile*

Here, you see that the very first character

is a hyphen (-). This indicates that the file is a regular file.

Special Characters for Different File

Types
Character File Type
- Regular file
l Symbolic link
c Character special file
b Block special file
p Named pipe
s Socket
d Directory file
I'll

To obtain file type information about a

directory, you must specify the -d option along with the -l option

NOTE:
Usually you need to know whether a

particular file is a binary program, a shell script, or a library. In these instances, the

file program is very useful.
It is invoked as follows:
file filename

Here, filename is the name of the file

you want to examine. As an example, on my system, the command
$ file /sbin/sh

produces the following output:

/sbin/sh: ELF 32-bit MSB executable

SPARC Version 1, statically linked,
stripped


7. LINK:

A symbolic link is a special

file that points to another file on the system.

ln -s source destination
* like a shortcut as in Windows

8.

You can access UNIX devices through

reading and writing to device files.
These device files are access points to

the device within the file systems.
Usually, device files are located under

the /dev directory.

The two main types of device files are

l Character special files
l Block special files

crw------- 1 ranga users 4, 0 Feb 7 13:47

/dev/tty0
The first letter in the output is c,

therefore you know that this particular file is a character special
file, but you also see two extra numbers

before the date. The first number is called the major number and
the second number is called the minor

number. UNIX uses these two numbers to identify the device driver
that this file communicates with.


9.Viewing Permissions

You can display the permissions of

a file using the ls -l command. For example, the following command
$ ls -l /home/ranga/.profile
produces the following output:
-rwxr-xr-x 1 ranga users 2368 Jul 11 15:57

.profile*
Because the first character is a hyphen (-),

you know that this is a regular file. Several characters appear
after this hyphen. The first three

characters indicate the permissions for the owner of the file, the next three
characters indicate the permissions for

the group the file is associated with, and the last three characters
indicate the permissions for all other

users


10. SID AND GID >>Additional permissions

are given to

programs via a mechanism known as the Set User ID ( SUID) and Set Group ID (

SGID) bits. When you execute a program that has the SUID bit enabled, you inherit

the permissions of that program's owner. Programs that do not have the SUID bit set

are run with the
permissions of the user who started the

program.

This is true for SGID as well. Normally

programs execute with your group permissions, but instead your
group will be changed just for this

program to the group owner of the program.
As an example, the passwd command,

used to change your password, is owned by the root and has the set SUID bit

enabled. When you execute it, you effectively become root while the command

runs.


The SUID and SGID bits will appear as

the letter "s" if the permission is available. The SUID "s"
bit will be located in the permission bits

where the owners execute permission would normally reside. For
example, the command
$ ls -l /usr/bin/passwd
produces the following output:
-r-sr-xr-x 1 root bin 19031 Feb 7 13:47

/usr/bin/passwd*

which shows that the SUID bit is set and

that the command is owned by the root. A capital letter S in the
execute position instead of a lowercase s

indicates that the execute bit is not set.


11. Setting Permissions -Quick Tutorial.


Letter Represents
u Owner
g Group
o Other
a All

actions

Symbol Represents
+ Adding permissions to the file
- Removing permission from the file
= Explicitly set the file permissions

permissions
Letter Represents
r Read
w Write
x Execute
s SUID or SGID

To give the "world" read access to all

files in a directory, you can use one of the following commands:
$ chmod a=r *
or
$ chmod guo=r *

To set the SUID and SGID bits for your

home directory, try the following:
$ cd ; chmod ug+s .



12. OCTAL METHOD:


Read permission has a value of 4
l Write permission has a value of 2
Execute permission has a value of

1
Adding the value of the permissions

that you want to grant will give you a number between 0 and 7.

This number will be used to specify the

permissions for the owner, group, and finally the other category.
Setting SUID and SGID using the octal

method places these bits out in front of the standard permissions.
The permissions SUID and SGID take on

the values 4 and 2, respectively.


In order to set the "world" read access to

all files in a directory, do this:
chmod 0444 *

13.Chown & Chgrp:


chown ranga:

/home/httpd/html/users/ranga
changes the owner of the given directory

to the user ranga.

The chown command will recursively

change the ownership of all files when the -R option is included. For
example, the command
chown -R ranga:

/home/httpd/html/users/ranga
changes the owner of all the files and

subdirectories located under the given directory to be the user ranga.

14.Background Processes That Require Input


If you run a background process that

requires input and do not redirect it to read a file instead of the
keyboard, the process stops. If you have

process and job monitoring enabled, pressing Enter at an empty
command prompt or starting a command

returns a message.

The following is an example of running a
command in the background that needs

input (using a simple program I created that is not part of UNIX):
$ i_need_input &

[1] + Stopped (SIGTTIN) i_need_input &
On some systems the message looks like

the following:
[1] + Stopped (tty input) i_need_input &
SIGTTIN (seen in the first example) is a

signal ( SIG) that tells me the program is waiting for terminal ( TT)
input ( IN)


15.
You can determine which key performs

which function by using the stty command. By entering
$ stty -a
you are shown the following, along with

a lot of other information:
intr = ^C; quit = ^\; erase = ^H; kill = ^U;

eof = ^D; eol = ^@
eol2 = ^@; start = ^Q; stop = ^S; susp =

^Z; dsusp = ^Y; reprint = ^R
discard = ^O; werase = ^W; lnext = ^


16.
When a foreground process is suspended,

a command prompt enables you to enter more commands; the
original process is still in memory but is

not getting any CPU time.

To resume the foreground process, you
have two choices--background and

foreground.

The bg command enables you to resume

the suspended
process in the background; the fg

command returns it to the foreground

Eg:
$ long_running_process
^Z[1] + Stopped (SIGTSTP)

long_running_process
$ long_running_process2
^Z[2] + Stopped (SIGTSTP)

long_running_process2
$
To move the first one to the background,

I use the following:
$ bg %1
[1] long_running_process &
$
The second process is still suspended

and can be moved to the background as follows:
$ bg %2
[2] long_running_process2 &



17. NoHup:


You can prevent a background process

from terminating, which is the default action, when you sign off or
are disconnected. The nohup command

prevents your process from getting the HUP (Hang UP) signal and
enables it to continue processing.


18:You can use exec to change your

shell interpreter completely without creating a subshell. To convert from ksh to csh,

you can use the following:

exec csh

19.Daemons--Daemons are system-related

background processes that often run with the permissions of root and services

requests from other processes.


Background Processes --Background

processes are autonomous processes that run under UNIX without requiring user

interaction.

20._FRUIT : Valid Variable Name in

SHELL SCRIPTS.

21. You can access all the items in an array in

one of the following ways:

${name[*]}
${name[@]}

22.The shell provides a way to mark variables as

read-only by using the readonly command. After a variable is marked read-only, its

value cannot be changed.



Consider the following commands:
$ FRUIT=kiwi
$ readonly FRUIT

23.Both scalar and array variables are unset

using the unset command:

unset name
// Unset ->Forget the Value Which is no

longer Needed...

24.Any characters within single quotes are

quoted just as if


25.File Test Options:


-b file True if file exists and is a block

special file.
-c file True if file exists and is a character

special file.
-d file True if file exists and is a

directory.
-e file True if file exists.
-f file True if file exists and is a regular

file.
-g file True if file exists and has its SGID

bit set.
-h file True if file exists and is a symbolic

link.
-k file True if file exists and has its

"sticky" bit set.
-p file True if file exists and is a named

pipe.
-r file True if file exists and is readable.
-s file True if file exists and has a size

greater than zero.
-u file True if file exists and has its SUID

bit set.
-w file True if file exists and is writable.
-x file True if file exists and is

executable.
-O file True if file exists and is owned by

the effective user ID.

26.Until loop ..


27. The basename command takes an absolute

or relative path and returns the file or directory name. Its basic

syntax is
basename file

28.Because the filenames and the column

headings are

both strings, you need the %s

format sequence for formatting. Then you need to pick a maximum size for the
filenames. If you pick 32 as the

maximum size of your format sequence, the first column becomes %32s.
Because you don't really care about the

size of the second column, you can stick with %s for that column.
With these changes your script becomes
#!/bin/sh
printf "%32s %s\n" "File Name" "File Type"


29.