Make for Windows: NMake | What is Nmake?

windows-nmake

Make for Windows: NMake

What is Nmake?
NMAKE is Microsoft’s implementation of the make tool. The Microsoft Program Maintenance Utility (NMAKE.EXE) is a 32-bit tool that builds projects based on commands contained in a description file.

Another definition found on web as well
nmake is the “make” program for Visual Studio. A “make” program builds (makes) an executable and/or package by reading a set of “make” files. These files are essentially scripts that specify what is to be made, what files (header, source code, resource) are needed for each output file, etc. So nmake can be used to completely automate the process.

A frequently asked question: “Where can I find make for Windows?“. The answer is: “Download and use NMake“.

Downloading NMake
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q132084

Direct Downloan Link of Nmake
http://download.microsoft.com/download/vc15/patch/1.52/w95/en-us/nmake15.exe

Installing NMake

Run the downloaded executable to extract the files. Copy both the NMAKE.EXE and the NMAKE.ERR file to your Perl bin directory, normally C:\Perl\bin. Make sure that you copy the NMAKE.ERR file as well.

1. Download nmake15.exe

2. Double click on nmake15.exe. It will generate 3 files: nmake.exe, nmake.err and readme.txt.

3. Copy nmake.exe and nmake.err to \perl\bin, which is where ActivePerl executable files are located.

4. Now try the nmake command in a command window. If you see the following message, NMake 1.5 is installed correctly:

>nmake
Microsoft (R) Program Maintenance Utility   Version 1.50    Copyright (c) Microsoft Corp 1988-94. All rights reserved.
NMAKE : fatal error U1064: MAKEFILE not found and no target specified    Stop.

Example of an NMake session

Normally building Perl modules and installing them consist of the following steps:

perl Makefile.pl
make
make test
make install

Reference:
http://msdn.microsoft.com/en-us/library/dd9y37ha%28v=vs.71%29.aspx

Tagged : / / / / / / / / / / / /

Versioning in Software Configuration Management | SCM Versioning Guide

versioning-in-software-configuration-management

Versioning in Software Configuration Management?

Reference: This article has been take out from Book Called “The Build Master: Microsoft’s Software Configuration Management Best Practices”

Why Worry About Versioning?

  • Having a good version scheme for your software is important for several reasons. The following are the top five things a version scheme allows you to do (in random order):
  • Track your product binaries to the original source files.
  • Re-create a past build by having meaningful labels in your source tree.
  • Avoid “DLL hell” —multiple versions of the same file (library in this case) on a machine.
  • Help your setup program handle upgrades and service packs.
  • Provide your product support and Q/A teams with an easy way to identify the bits they are working with.

So, how do you keep track of files in a product and link them back to the owner? How can you tell that you are testing or using the latest version of a released file? What about the rest of the reasons in the list? This chapter describes my recommendations for the most effective and easiest way to set up and apply versioning to your software. Many different schemes are available, and you should feel free to create your own versioning method.

Ultimately, like most of the other topics in this book, the responsibility to apply versioning to the files in a build tends to fall into the hands of the build team. That might be because it is usually the build team that has to deal with the headaches that come from having a poor versioning scheme. Therefore, it is in their best interest to publish, promote, and enforce a good versioning scheme. If the build team does not own this, then someone who does not understand the full implications of versioning will make the rules. Needless to say, this would not be desirable for anybody involved with the product.

What is the best way to accomplish this? Let’s start with the version number and work our way down.

File Versioning

Every file in a product should have a version number; a four-part number separated by periods such as the one that follows seems to be the established best practice. There are many variations of what each part represents. I will explain what I think is the best way of defining these parts.

<major version>.<minor version>.<build number>.<revision>

Major version— The component owner usually assigns this number. It should be the internal version of the product. It rarely changes during the development cycle of a product release.

Minor version— The component owner usually assigns this number. It is normally used when an incremental release of the product is planned instead of a full feature upgrade. It rarely changes during the development cycle of a product release.

Build number— The build team usually assigns this number based on the build that the file was generated with. It changes with every build of the code.

Revision— The build team usually assigns this number. It can have several meanings: bug number, build number of an older file being replaced, or service pack number. It rarely changes. This number is used mostly when servicing the file for an external release.

Build Number

Each build that is released out of the Central Build Lab should have a unique version stamp (also known as the build number). This number should be incremented just before a build is started. Don’t use a date for a build number or mix dates into a version number simply because there are so many date formats out there that it can be difficult to standardize on one. Also, if you have more than one build on a given date, the naming can get tricky. Stick with an n=n+1 build number. For example, if you release build 100 in the morning and rebuild and release your code in the afternoon, the afternoon build should be build 101. If you were to use a date for the build number, say 010105, what would your afternoon build number be? 010105.1? This can get rather confusing.

How Versioning Affects Setup

Have you ever met someone who reformats his machine every six months because “it just crashes less if I do” or it “performs better?” It might sound draconian, but the current state of component versioning and setup makes starting from scratch a likely solution to these performance issues, which are further complicated by spyware.

Most of the problems occur when various pieces of software end up installing components (DLLs and COM components) that are not quite compatible with each other or with the full set of installed products. Just one incorrect or incorrectly installed DLL can make a program flaky or prevent it from starting up. In fact, DLL and component installation is so important that it is a major part of the Windows logo requirement.

If you are involved in your product’s setup, or if you are involved in making decisions about how to update your components (produce new versions), you can do some specific things to minimize DLL hell and get the correct version of your file on the machine.

Installing components correctly is a little tricky, but with these tips, you can install your components in a way that minimizes the chance of breaking other products on your own.

Install the Correct Version of a Component for the Operating System and Locale
If you have operating system (OS)-specific components, make sure your setup program(s) check which OS you are using and install only the correct components. Also, you cannot give two components the same name and install them in the same directory. If you do, you overwrite the component on the second install on a dual-boot system. Note that the logo requirements recommend that you avoid installing different OS files if possible. Related to this problem is the problem caused when you install the wrong component or typelib for the locale in use, such as installing a U.S. English component on a German machine. This causes messages, labels, menus, and automation method names to be displayed in the wrong language.

Write Components to the Right Places
Avoid copying components to a system directory. An exception to this is if you are updating a system component. For that, you must use an update program provided by the group within Microsoft that maintains the component.

In general, you should copy components to the same directory that you copy the EXE. If you share components between applications, establish a shared components directory. However, it is not recommended that you share components between applications. The risks outweigh the benefits of reduced disk space consumption.

Do Not Install Older Components Over Newer Ones
Sometimes, the setup writer might not properly check the version of an installed component when deciding whether to overwrite the component or skip it. The result can be that an older version of the component is written over a newer version. Your product runs fine, but anything that depends on new features of the newer component fails. Furthermore, your product gets a reputation for breaking other products. We address the issue of whether it makes sense to overwrite components at all. But if you do overwrite them, you don’t want to overwrite a newer version.

“Copy on Reboot” If Component Is in Use
Another common mistake is to avoid dealing with the fact that you cannot overwrite a component that is in use. Instead, you have to set up the file to copy on reboot. Note that if one component is in use, you probably should set up all the components to copy on reboot. If you don’t, and if the user doesn’t reboot promptly, your new components could be mixed with the old ones.

Register Components Correctly; Take Security into Account
Sometimes setups don’t properly register COM components correctly, including the proxy and stub. Note that Windows CE requires that you also register DLLs. Note, too, that when installing DCOM components, you must be vigilant about permissions and security.

Copy Any Component That You Overwrite
It is smart to make a copy of any component that you overwrite before you overwrite it. You won’t want to put it back when you uninstall unless you’re sure that no product installed after yours will need the newer component—a difficult prediction! But by storing the component in a safe place, you make it possible for the user to fix his system if it turns out that the component you installed breaks it. You can let users know about this in the troubleshooting section of your documentation, the README file, or on your Web site. Doing this might not save a call to support, but it does at least make the problem solvable. If the component is not in use, you can move it rather than copying it. Moving is a much faster operation.

Redistribute a Self-Extracting EXE Rather Than Raw Components
If your component is redistributed by others (for instance, your component is distributed with several different products, especially third-party products), it is wise to provide a self-extracting EXE that sets up your component correctly. Make this EXE the only way that you distribute your component. (Such an EXE is also an ideal distribution package for the Web.) If you just distribute raw components, you have to rely on those who redistribute your components to get the setup just right. As we have seen, this is pretty easy to mess up.

Your EXE should support command-line switches for running silently (without a UI) and to force overwriting, even of newer components, so that product support can step users through overwriting if a problem arises.

If you need to update core components that are provided by other groups, use only the EXE that is provided by that group.

Test Setup on Real-World Systems
If you’re not careful, you can install all your setup testing on systems that already happen to have the right components installed and the right registry entries made. Be sure to test on raw systems, on all operating systems, and with popular configurations and third-party software already installed. Also, test other products to make sure they still work after you install your components.

Tagged : / / / / / / / / / / / / / / / / /

Hardware Configuration – What are the Hardware Requirements for Build Server?

build-server-hardware-configuration-requirements

Hardware Configuration – Hardware Requirements for Build Server

Reference: The Build Master: Microsoft’s Software Configuration Management Best Practices

At a minimum, the build lab should have four machines:

Server that contains the Source Code Control program— This is your product. Do you really want this server residing someplace where you have little control over this box?

Debug build machine for the mainline builds— If you don’t separate your debug and release machines, you will accidentally ship debug binaries, which is not a good thing.

Release build machine for the mainline builds— This is a “golden goose” that turns out the “gold eggs” of your company or group. Treasure this machine like a princess, and guard it like all the king’s fortunes.

Internal release share server— This is one more piece of hardware that stores the “bread and butter” of the group or company. Don’t give up control of this hardware to anyone unless your IT department reports through your development group.

Hardware Requirements
Each machine in the preceding list should meet the following requirements:

Number of processors— This depends on the build tool you use. One is usually sufficient, because few build tools really take advantage of multiple processors.

Processor speed— The lab budget dictates this, but the faster the processor, the better it is.

Amount of installed RAM— Max out the machine. RAM is relatively cheap these days, especially when you consider the performance increase you get. Increasing the RAM is usually the first upgrade done when trying to improve the performance of any computer.

Number of hard drives— A minimum of two drives (or partitions) is preferred:

Drive 1 (C:) is for the operating system and installed applications.

Drive 2 (D:) is for building binaries, release shares, or the source database; the minimum space required is roughly ten times the space needed to build your application.

The split partitions are good because if you ever need to format or blow away a drive due to corruption, only part of the project will be affected. The recovery is much faster and easier.

Hard drive type— This is most likely SCSI, but it could be IDE.

Number of power supplies— If you purchase server class hardware (pizza boxes) that belong in racks, you need to consider how many power supplies to order.

Motherboard BIOS version— This does make a difference. Make sure you note what is being used and standardize on it.

Tagged : / / / / / / / / / / / / / /

More Important Build Definitions | Different Build Definitions | Build Terminologies

build-definitions

More Important Build Definitions

Reference: The Build Master: Microsoft’s Software Configuration Management Best Practices

It is also important for groups or teams to define these terms on a project-wide basis so that everyone is clear on what he is getting when a build is released.

Pre-build— Steps taken or tools run on code before the build is run to ensure zero build errors. Also involved are necessary steps to prepare the build and release machines for the daily build, such as checking for appropriate disk space.

Post-build— Includes scripts that are run to ensure that the proper build verification tests (BVTs) are run. This also includes security tests to make sure the correct code was built and nothing was fused into the build.

Clean build— Deleting all obj files, resource files, precompiled headers, generated import libraries, or other byproducts of the build process. I like to call this cleaning up the “build turds.” This is the first part of a clean build definition. Most of the time, build tools such as NMake.exe or DevEnv.exe handle this procedure automatically, but sometimes you have to specify the file extensions that need to be cleaned up. The second part of a clean build definition is rebuilding every component and every piece of code in a project. Basically the perfect clean build would be building on a build machine with the operating system and all build tools freshly installed.

Incremental build— The secret to getting out a daily build to the test team, regardless of circumstances, is to perform incremental builds instead of daily clean builds. This is also the best way that you can maintain quality and a known state of a build. An incremental build includes only the code of the source tree that has changed since the previous build. As you can guess, the build time needed for an incremental build is just a fraction of what a clean build takes.

Continuous integration build— This term is borrowed from the extreme programming (XP) practice. It means that software is built and tested several times per day as opposed to the more traditional daily builds. A typical setup is to perform a build every time a code check-in occurs.

Build break— In the simplest definition, a build break is when a compiler, linker, or other software development tool (such as a help file generator) outputs an error caused by the source code it was run against.

Build defect— This type of problem does not generate an error during the build process; however, something is checked into the source tree that breaks another component when the application is run. A build break is sometimes referred to or subclassed as a build defect.

Last known good (LKG) or internal developers workstation (IDW) builds— These terms are used as markers to indicate that the build has reached a certain quality assurance criterion and that it contains new high-priority fixes that are critical to the next baseline of the shipping code. The term LKG originated in the Visual Studio team, and IDW came from the Windows NT organization. LKG seems to be the more popular term at Microsoft.

Tagged : / / / / / / / / / / / / / / / / / /

Different Perforce Tools and Their Short Summary | Know About Different Perforce tools

different-perforce-tools

Different Perforce Tools and Their Short Summary

Clients
P4V: Visual Client – (Included in the P4V Installer)
Provides access to versioned files through a graphical interface and also includes tools for merging and visualizing code evolution.
P4Merge: Visual Merge Tool – (Included in the P4V Installer)
Provides graphical three-way merging and side-by-side file comparisons
P4: Command-Line Client – (Included in the Perforce Server Windows Installer)
(Included in the Perforce Server Windows Installer)
P4Web: Web Client – (Included in the P4Web Installer)
Provides convenient access to versioned files through popular web browsers

Server
P4D: Server – (Included in the Perforce Server Windows Installer)
Stores and manages access to versioned files, tracks user operations and records all activity in a centralized database.
P4P: Proxy Server – (Included in the Perforce Server Windows Installer)
A self-maintaining proxy server that caches versioned files remotely on distributed networks.

Plug-ins & Integrations
P4WSAD: Plug-in for Eclipse and WebSphere Studio
Access Perforce from within the Eclipse IDE and the Rational/WebSphere Studio WorkBench family of products
P4SCC: SCC Plug-in – (Included in the P4V Installer)
Enables you to perform Perforce operations from within IDEs that support the Microsoft SCC API including Visual Studio.
P4EXP: Plug-in for Windows Explorer – (Included in the P4V Installer)
Allows Windows users direct access to Perforce.
P4DTG: Defect Tracking Gateway – (Included in the P4DTG Installer)
Allows information to be shared between Perforce’s basic defect tracking system and external defect tracking systems.
P4GT: Plug-in for Graphical Tools
Provides seamless access to version control for files from within Adobe Photoshop, SoftImage XSI, Autodesk’s 3ds max, and Maya
P4OFC: Plug-in for Microsoft Office
Allows documents to be easily stored and managed in Perforce directly from Microsoft Word, Excel, PowerPoint and Project.

Tools & Utilities
P4Report: Reporting System
Supports leading tools such as Crystal Reports, Microsoft Access, and Microsoft Excel, or any reporting
tool that interfaces with an ODBC data source.
P4Thumb: Thumbnail Generator
Creates thumbnails of graphics files managed by Perforce and stores the thumbnails in the server for presentation in P4V.
P4FTP: FTP Plug-in
Allows FTP clients like Dreamweaver, Netscape, and Internet Explorer to access files in Perforce depots.’
Links to Download: http://www.perforce.com/perforce/downloads/platform.html

Good Video Tutorial Links
http://www.perforce.com/perforce/media_library/tutorials.html
http://www.perforce.com/perforce/demo/testdrive.html

Tagged : / / / / / / / / / / / / / / / / / /

Main Responsibilities of the Linux System Administrator | What Linux System Administrators do ?

linux-system-administrators-responsibilities

Main Responsibilities of the Linux System Administrator is as follows:

  1. Maintaining User Accounts
  2. Security
  3. Managing the disk space and Backup
  4. Provisiom the new Linux Server based on the need
  5. Linux Server Updates and Patching
  6. Authentication and Authorization Management
  7. Trubleshooting of Linux Severs and QA Deployments
  8. Managing the Large number of VMS in VMWARE
  9. Montoring all the vms and their health
  10. Montoring Major Important Services
  11. Backup & Restore all the imporant data of the servers
  12. Server and OS process monitoring
  13. Disk managment and montoring

The Administrator’s Privileges:

  1. Change the contents or attributes of any file like its permission and ownership
  2. He can delete any file eith rm even if it is write-protected.
  3. Initiate or Kill Any Process
  4. Change any user’s password without knowing the existing one
  5. Set the system clock with date
  6. Limit the maximum size of files that users are permitted to create with ulimlit
  7. Controls users access to the scheduling services like at and cron
  8. Control users access to many networking services like Telnet, FTP, etc

Tagged : / / / / / / / / / / / / / / / / /

Interview Questions & Answer for Build & Release Engineers

build-release-engineer-interview-questions-answer

I get many emails and linkedin personal message about sharing interview questions for Build & Release Engineer and Configuration Engineer.

I have asked some of my friends to share too and now here is the consolidated list of interview questions which is very much commonly asked in interview. if you like it, please share with other members and contribut it too. I will add in this article in next update. mail me at rajesh at scmgalaxy.com

Tag Line:

Interview Questions & Answer for Build Engineer
Interview Questions & Answer for Release Engineer
Interview Questions & Answer for Configuration Engineer
Interview Questions & Answer for Build & Release Engineer

Interview Questions and Answer on configuration management?

  • What do you think about configuration management?
  • What do you understand about Change Management?
  • branching methodologies and what currently theya re using it. Show with some example with pros and cons
  • Concept of Merging and Why do we need?

Interview Questions and Answer on build Management?

  • What do you think about build Management?
  • What are the key benefit of build Automation and what are the key inputs to automate the build process in the project?
  • Discuss about tools and technology which help to automate the entire build cycle.
  • What is Continuous Build Integration and How this is useful for the project?
  • What is daily build & nightly builds and what are the process need to set up to Automate & monitor consistently.
  • Explain in details for writing build sciprt for any project

Interview Questions and Answer on release Management?

  • What is release Management?
  • Talk about Release Management on several platforms?
  • What do you understand about Packaging and Deployment?
  • How to Automate Remote Deployment of Builds on Development & Test Servers?

Some Generic Interview questions for Build and Release and SCM Professionals.

  • What is workflow management. exmplain this in details
  • What do you understand about Code Coverage? Describe repective tools & utilities.
  • Describe the Integrate Packaging scripts & Test Automation scripts with build & Monitor build verification test status and tools.
  • How to co-ordinate with development team to increase their productiavity.
  • What do you understand about multisite project
  • How SCM team perform integration and co-ordination between Dev and QA
  • How do you Troubleshooting your build server. What kind of issues you get in build server or cm server?
  • java Comipler issues in build server and their version
  • C++ compiler issues in build server and their version
  • What are basic skills required for Perforce administration including Command Line info.
  • Explain the best practice for Setup process & maintain the Archive of software releases (internal & external) & license management of Third Party Libraries
  • Concept of labeling, branching and merging in perforce / svn and git
  • Best Practice and strategy of branching and merging in perforce
  • Talk about agile and attempts to minimize risk by developing software in short iterations.
  • Why agile on Iterative development model and Waterfall software development model?
  • What are Bug /Issue Tatcking tools available and descibe them.

Source code control best practice?

  • Use a reliable and dedicated server to house your code.
  • Backup your code daily.
  • Test your backup and restore processes.
  • Choose a source control tool that fits your organization’s requirements.
  • Perform all tool specific administrative tasks.
  • Keep your code repositories as clean as possible.
  • Secure access to your code.

Describe software build best practices?

  • Fully automated build process
  • Build repeatability
  • Build reproducibility
  • Build process adherence

Tools Comparison and Differences

  • Difference Between CVS and SVN
  • Difference Between perforce and SVN
  • Difference Between perforce and Clearcasee
  • Difference Between VSS and TFSC
  • Difference Between perforce and MKS
  • Difference Between Bea Weblogic and IBM Websphere
Tagged : / / / / / / / / / / / / / / /

Most asked Perl Interview Questions and Answers

perl-interview-questions-answers

What is Perl one-liner?

There are two ways a Perl script can be run:

a)from a command line, called one-liner, that means you type and execute immediately on the command line. You’ll need the -e option to start like “perl -e “print “Hello”;”. One-liner doesn’t mean one Perl statement. One-liner may contain many statements in one line.

b)from a script file, called Perl program.

Assuming both a local($var) and a my($var) exist, what’s the difference between ${var} and ${“var”}?

${var} is the lexical variable $var, and ${“var”} is the dynamic variable $var.

Note that because the second is a symbol table lookup, it is disallowed under `use strict “refs”‘. The words global, local, package, symbol table, and dynamic all refer to the kind of variables that local() affects, whereas the other sort, those governed by my(), are variously knows as private, lexical, or scoped variable.

Name all the prefix dereferencer in perl?

The symbol that starts all scalar variables is called a prefix dereferencer. The different types of dereferencer are.

(i) $-Scalar variables

(ii) %-Hash variables

(iii) @-arrays

(iv) &-subroutines

(v) Type globs-*myvar stands for @myvar, %myvar.

What exactly is grooving and shortening of the array?

You can change the number of elements in an array simply by changing the value of the last index of/in the array $#array. In fact, if you simply refer to a non existent element in an array perl extends the array as needed, creating new elements. It also includes new elements in its array.

What are the three ways to empty an array?

The three different ways to empty an array are as follows

  1. You can empty an array by setting its length to a negative number.
  2. Another way of empting an array is to assign the null list ().
  3. Try to clear an array by setting it to undef, but be aware when you set to undef.

How do you work with array slices

An array slice is a section of an array that acts like a list, and you indicate what elements to put into the slice by using multiple array indexes in square brackets. By specifying the range operator you can also specify a slice.

What is meant by splicing arrays explain in context of list and scalar.

Splicing an array means adding elements from a list to that array, possibly replacing elements now in the array. In list context, the splice function returns the elements removed from the array. In scalar context, the splice function returns the last element removed.

What are the different types of perl operators?

Please refer following URL..Perl Operators

What are the two different types of data perl handles?
Perl handles two types of data they are
(i) Scalar Variables and
(ii) Lists
Scalar variables hold a single data item whereas lists hold multiple data items.

What are scalar variables?
Scalar variables are what many programming languages refer to as simple variables. They hold a single data item, a number, a string, or a perl reference. Scalars are called scalars to differentiate them from constructs that can hold more than one item, like arrays.

Explain about lists?
A list is a construct that associates data elements together and you can specify a list by enclosing those elements in parenthesis and separating them with commas. They could themselves be arrays, hashes or even other lists. Lists do not have a specific list data type.

Name all the prefix dereferencer in perl?
The symbol that starts all scalar variables is called a prefix dereferencer. The different types of dereferencer are.
(i) $-Scalar variables
(ii) %-Hash variables
(iii) @-arrays
(iv) &-subroutines
(v) Type globs-*myvar stands for @myvar, %myvar.

Explain about an ivalue?
An ivalue is an item that can serve as the target of an assignment. The term I value originally meant a “left value”, which is to say a value that appears on the left. An ivalue usually represents a data space in memory and you can store data using the ivalues name. Any variable can serve as an ivalue.

How does a “grep” function perform?
Grep returns the number of lines the expression is true. Grep returns a sublist of a list for which a specific criterion is true. This function often involves pattern matching. It modifies the elements in the original list.

Explain about Typeglobs?
Type globs are another integral type in perl. A typeglob`s prefix derefrencer is *, which is also the wild card character because you can use typeglobs to create an alias for all types associated with a particular name. All kinds of manipulations are possible with typeglobs.

Is there any way to add two arrays together?

Of course you can add two arrays together by using push function. The push function adds a value or values to the end of an array. The push function pushes the values of list onto the end of the array. Length of an array can be increased by the length of list.

How to use the command shift?
Shift array function shifts off the first value of the array and returns it, thereby shortening the array by one element and moving everything from one place to the left. If you don’t specify an array to shift, shift uses @ ARGV, the array of command line arguments passed to the script or the array named @-.

Which has the highest precedence, List or Terms? Explain?
Terms have the highest precedence in perl. Terms include variables, quotes, expressions in parenthesis etc. List operators have the same level of precedence as terms. Specifically, these operators have very strong left word precedence.

What is a short circuit operator?
The C-Style operator, ll, performs a logical (or) operation and you can use it to tie logical clauses together, returning an overall value of true if either clause is true. This operator is called a short-circuit operator because if the left operand is true the right operand is not checked or evaluated.

What are the different forms of goto in perl? Explain?
The three forms of goto are as follows. They are
(i) Goto label
(ii) Goto name
(iii) Goto expr
The first form, goto LABEL, transfers execution to the statement labeled LABEL. The second form, goto EXPR, expects EXPR to evaluate to a label. The last form goto &name is used with subroutines. This goto statement is used only when there is a necessity as it can create havoc in a program.

What are the different types of eval statements?
There are two different types of eval statements they are eval EXPR and eval BLOCK. Eval EXPR executes an expression and eval BLOCK executes BLOCK. Eval Block executes an entire block, BLOCK. First one is used when you want your code passed in the expression and the second one is used to parse the code in the block.

Explain about returning values from subroutines (functions)?
The return value of the subroutine is the value of the last expression evaluated or you can explicitly use a return statement to exit the subroutine specifying the return value. That return value is evaluated in the appropriate content depending on the content of the subroutine call.

What is sed?
sed is stream editor, a Unix tool for working with streams of text data. See the awful truth about sed.

How do you substitute strings with sed?
Use ’s/old/new’ command, so sed ’s/hello/goodbye/’ would substitute the occurrence of the word hello to goodbye.

How do you inject text with sed?
& in the substitution string defines the pattern found in the search string. As an example, here’s us trying to find a word ‘hello’ and replacing it with ‘hello and how are you’:
echo ‘hello there’ | sed ’s/^hello/& and how are you/’

Can I find several patterns and refer to them in the replacement string?
Yes, use (pattern) and then refer to your patterns as \1, \2, \3 and so on.

If the string is ‘old old old’ and I run ’s/old/new’, I get ‘new old old’ as the result. I need ‘new new new‘.
You forgot the global modifier, which would replace every occurrence of the pattern with the substitution. ’s/old/new/g‘ will work.

But I want ‘old old new’ from the previous example. – Just use the numeric modifier saying you want the third occurrence to be replaced. ’s/old/new/3‘ will work.

I wrote a rather complex sed script. How do I save and run it?
Assuming that your file is named myscript1.sed, you can invoke sed -f myscript1.sed.

How do I delete trailing whitespaces from each line?
sed ’s/[ \t]*$//’ Here we’re replacing any occurrence of a space or a tab with nothing. Check sed one-liners for more examples.

How do you print just a few first lines of the file? – sed 1q will give you just the first line, sed 10q the first 10 lines.

How do you replace a pattern only if it’s found, so that it’s executed faster? – Nest the replacement statement: sed ‘/old/ s/old/new/g’ file.txt

How do you know the reference of a variable whether it is a reference,scaller, hash or array?
There is a ‘ref’ function that lets you know

What is the difference between ‘use’ and ‘require’ function?

Use: 1. the method is used only for modules (only to include .pm type file) 2. the included object are verified at the time of compilation. 3. No Need to give file extentsion. Require: 1. The method is used for both libraries ( package ) and modules 2. The include objects are varified at the run time. 3. Need to give file Extension.

What is the use of ‘chomp’ ? what is the difference between ‘chomp’ and ‘chop’?

Ans. ‘chop’ functiononly removes the last character completely ‘from the scaler, where as ‘chomp’ function only removes the last character if it is a newline. by default, chomp only removes what is currently defined as the $INPUT_RECORD_SEPARATOR. whenever you call ‘chomp ‘, it checks the value of a special variable ‘$/’. whatever the value of ‘$/’ is eliminated from the scaler. by default the value of ‘$/’ is ‘n’

Print this array @arr in reversed case-insensitive order

Ans> @solution = sort {lc $a comp lc$b } @arr.

What is ‘->’ in Perl?

Ans. it is a symbolic link to link one file name to a new name. so lets say we do it like file1-> file2, if we read file1, we end up reading file2.

how do you check the return code of system call?

System calls “traditionally” returns 9 when successful and 1 when it fails. system (cmd) or die “Error in command”;

#create directory if not there
if (! -s “$temp/engl_2/wf”){ System “mkdir -p $temp/engl_2/wf”; } if (! -s “$temp/backup_basedir”){ system “mkdir -p $temp/backup_basedir”; } ${pack_2} = -M “${temp}/engl_2/wf/${wf_package_name}.data”; ${new_pack}= -M “{pack}/package.data”; What is the use of -M and -s in the above script?

Ans. -s means is filename a non-empty file -M how long since filename modified?

How to substitute a particular string in a file containing million of record?

Ans. perl -p -ibak -e ‘s/search_str/replace_str/g’ filename

I have a variable named $objref which is defined in main package. I want to make it as a Object of class XYZ. how could I do it?

Ans. use XYZ my $objref =XYZ -> new() OR, bless $objref, ‘XYZ’;

what is meant by a ‘pack’ in perl?

Pack Converts a list into a binary representation. Takes an array or list of values and packs it into a binary structure, returning the string containing the structure It takes a LIST of values and converts it into a string. The string contaings a con-catenation of the converted values. Typically, each converted values looks like its machine-level repesentation. for example, on 32-bit machines a converted integer may be representated by a sequence of 4 bytes.

how to implement stack in Perl?

through push() and shift() function. push adds the element at the last of array and shift() removes from the beginning of an array.

What is Grep used for in Perl?

Grep is used with regular expression to check if a parituclar value exist in an array. it returns 0 it the value does not exists, 1 otherwise.

How to code in Perl to implement the tail function in unix?

And. You have to maintain a structure to store the line number and the size of the file at that time eg. 1-10bytes, 2-18bytes.. you have a counter to increase the number of lines to find out the number of lines in the file. once you are through the file, you will know the size of the file at any nth line, use ‘sysseek’ to move the file pointer back to that position (last 10) and thens tart reading till the end.

15. How do you navigate thorugh an XML documents?

Ans. You can use the XML::DOM navigation methods to navigate thorugh an XML::DOM node tree and use the getnodevalue to recover the data. DOM Parser is used when it is neede to do node operation. Instead we may use SAX parser if you require simple processing of the xml structure.

Why do you use Perl?

* Perl is a powerful free interpreter.
* Perl is portable, flexible and easy to learn.

How do I set environment variables in Perl programs?

You can just do something like this:
$ENV{‘PATH’} = ‘…’;
As you may remember, “%ENV” is a special hash in Perl that contains the value of all your environment variables.
Because %ENV is a hash, you can set environment variables just as you’d set the value of any Perl hash variable. Here’s how you can set your PATH variable to make sure the following four directories are in your path::

$ENV{‘PATH’} = ‘/bin:/usr/bin:/usr/local/bin:/home/yourname/bin’;

Which of these is a difference between C++ and Perl?
Perl can have objects whose data cannot be accessed outside its class, but C++ cannot.

Perl can use closures with unreachable private data as objects, and C++ doesn’t support closures. Furthermore, C++ does support pointer arithmetic via `int *ip = (int*)&object’, allowing you do look all over the object. Perl doesn’t have pointer arithmetic. It also doesn’t allow `#define private public’ to change access rights to foreign objects. On the other hand, once you start poking around in /dev/mem, no one is safe.

How to open and read data files with Perl

Data files are opened in Perl using the open() function. When you open a data file, all you have to do is specify (a) a file handle and (b) the name of the file you want to read from.
As an example, suppose you need to read some data from a file named “checkbook.txt”. Here’s a simple open statement that opens the checkbook file for read access: open (CHECKBOOK, “checkbook.txt”); In this example, the name “CHECKBOOK” is the file handle that you’ll use later when reading from the checkbook.txt data file. Any time you want to read data from the checkbook file, just use the file handle named “CHECKBOOK”.
Now that we’ve opened the checkbook file, we’d like to be able to read what’s in it. Here’s how to read one line of data from the checkbook file:
$record = < CHECKBOOK > ;
After this statement is executed, the variable $record contains the contents of the first line of the checkbook file. The “<>” symbol is called the line reading operator.
To print every record of information from the checkbook file

open (CHECKBOOK, “checkbook.txt”) || die “couldn’t open the file!”;
while ($record = < CHECKBOOK >) {
print $record;
}
close(CHECKBOOK);

How do I do fill_in_the_blank for each file in a directory?
Answer:Here’s code that just prints a listing of every file in the current directory:
#!/usr/bin/perl -w
opendir(DIR, “.”);
@files = readdir(DIR);
closedir(DIR);
foreach $file (@files) {
print “$file\n”;
}

How do I generate a list of all .html files in a directory?

Answer:
Here’s a snippet of code that just prints a listing of every file in the current directory that ends with the extension .html:
#!/usr/bin/perl -w
opendir(DIR, “.”);
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);
foreach $file (@files) {
print “$file\n”;
}

What happens when you return a reference to a private variable?

Perl keeps track of your variables, whether dynamic or otherwise, and doesn’t free things before you’re done using them.

How to turn on Perl warnings? Why is that important?

Perl is very forgiving of strange and sometimes wrong code, which can mean hours spent searching for bugs and weird results. Turning on warnings helps uncover common mistakes and strange places and save a lot of debugging time in the long run. There are various ways ofturning on Perl warnings:

* For Perl one-liner, use -w option on the command line.
* On Unix or Windows, use the -w option in the shebang line (The first # line in the script). Note: Windows Perl interpreter may not require it.
* For other systems, choose compiler warnings, or check compiler documentation.

What are scalar data and scalar variables?

Perl has a flexible concept of data types. Scalar means a single thing, like a number or string. So the Java concept of int, float, double and string equals to Perl\’s scalar in concept and the numbers and strings are exchangeable. Scalar variable is a Perl variable that is used to store scalar data. It uses a dollar sign $ and followed by one or more alphanumeric characters or underscores. It is case sensitive.

Why should I use the -w argument with my Perl programs?

Many Perl developers use the -w option of the interpreter, especially during the development stages of an application. This warning option turns on many warning messages that can help you understand and debug your applications.
To use this option on Unix systems, just include it on the first line of the program, like this:
#!/usr/bin/perl -w
If you develop Perl apps on a DOS/Windows computer, and you’re creating a program named myApp.pl, you can turn on the warning messages when you run your program like this:
perl -w myApp.pl

I want users send data by formmail but when they send nothing or call it from web site they will see error. codes in PHP like this: if (isset($HTTP_POST_VARS)){ ………. } else{ echo (“error lalalalal”) } How it will look in perl?

In php it will be like
if (isset($HTTP_POST_VARS)){
….
}
In perl, tried this.
if ($ENV{‘REQUEST_METHOD’} eq ‘POST’){
…..
}

What is the output of the following Perl program?
1 $p1 = “prog1.java”;
2 $p1 =~ s/(.*)\.java/$1.cpp/;
3 print “$p1\n”;

Answer:What is the output of the following Perl program?
1 $p1 = “prog1.java”;
2 $p1 =~ s/(.*)\.java/$1.cpp/;
3 print “$p1\n”;

prog1.cpp

Why are not Perls patterns regular expressions?

Because Perl patterns have backreferences.
A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extra memory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the classic sense of the term.

What does Perl do if you try to exploit the execve(2) race involving setuid scripts?

Sends mail to root and exits.
It has been said that all programs advance to the point of being able to automatically read mail. While not quite at that point (well, without having a module loaded), Perl does at least automatically send it.

How do I do < fill-in-the-blank > for each element in a hash?

Here’s a simple technique to process each element in a hash:

#!/usr/bin/perl -w

%days = (
‘Sun’ =>’Sunday’,
‘Mon’ => ‘Monday’,
‘Tue’ => ‘Tuesday’,
‘Wed’ => ‘Wednesday’,
‘Thu’ => ‘Thursday’,
‘Fri’ => ‘Friday’,
‘Sat’ => ‘Saturday’ );

foreach $key (sort keys %days) {
print “The long name for $key is $days{$key}.\n”;
}

How do I sort a hash by the hash key?

Suppose we have a class of five students.
Their names are kim, al, rocky, chrisy, and jane.

Here’s a test program that prints the contents
of the grades hash, sorted by student name:

#!/usr/bin/perl -w

%grades = (
kim => 96,
al => 63,
rocky => 87,
chrisy => 96,
jane => 79,
);

print “\n\tGRADES SORTED BY STUDENT NAME:\n”;
foreach $key (sort (keys(%grades))) {
print “\t\t$key \t\t$grades{$key}\n”;
}

The output of this program looks like this:

GRADES SORTED BY STUDENT NAME:
al 63
chrisy 96
jane 79
kim 96
rocky 87

}

How do you print out the next line from a filehandle with all its bytes reversed?

print scalar reverse scalar <FH>
Surprisingly enough, you have to put both the reverse and the <FH> into scalar context separately for this to work.

How do I send e-mail from a Perl/CGI program on a Unix system?

Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We’ll go through a quick example here.
Assuming that you’ve already have e-mail information you need, such as the send-to address and subject, you can use these next steps to generate and send the e-mail message:
# the rest of your program is up here …
open(MAIL, “|/usr/lib/sendmail -t”);
print MAIL “To: $sendToAddress\n”;
print MAIL “From: $myEmailAddress\n”;
print MAIL “Subject: $subject\n”;
print MAIL “This is the message body.\n”;
print MAIL “Put your message here in the body.\n”;
close (MAIL);

How to read from a pipeline with Perl
Example 1:

To run the date command from a Perl program, and read the output
of the command, all you need are a few lines of code like this:

open(DATE, “date|”);
$theDate = <DATE>;
close(DATE);

The open() function runs the external date command, then opens
a file handle DATE to the output of the date command.

Next, the output of the date command is read into
the variable $theDate through the file handle DATE.

Example 2:

The following code runs the “ps -f” command, and reads the output:

open(PS_F, “ps -f|”);
while (<PS_F>) {
($uid,$pid,$ppid,$restOfLine) = split;
# do whatever I want with the variables here …
}
close(PS_F);

Why is it hard to call this function: sub y { “because” }

Because y is a kind of quoting operator.
The y/// operator is the sed-savvy synonym for tr///. That means y(3) would be like tr(), which would be looking for a second string, as in tr/a-z/A-Z/, tr(a-z)(A-Z), or tr[a-z][A-Z].

What does $result = f() .. g() really return?

False so long as f() returns false, after which it returns true until g() returns true, and then starts the cycle again.
This is scalar not list context, so we have the bistable flip-flop range operator famous in parsing of mail messages, as in `$in_body = /^$/ .. eof()’. Except for the first time f() returns true, g() is entirely ignored, and f() will be ignored while g() later when g() is evaluated. Double dot is the inclusive range operator, f() and g() will both be evaluated on the same record. If you don’t want that to happen, the exclusive range operator, triple dots, can be used instead. For extra credit, describe this:
$bingo = ( a() .. b() ) … ( c() .. d() );

Why does Perl not have overloaded functions?

Because you can inspect the argument count, return context, and object types all by yourself.
In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they’re references and simple pattern matching like /^\d+$/ otherwise. In languages like C++ where you can’t do this, you simply must resort to overloading of functions.

What does read() return at end of file?

0
A defined (but false) 0 value is the proper indication of the end of file for read() and sysread().

What does new $cur->{LINK} do? (Assume the current package has no new() function of its own.)

$cur->new()->{LINK}
The indirect object syntax only has a single token lookahead. That means if new() is a method, it only grabs the very next token, not the entire following expression.
This is why `new $obj[23] arg’ does’t work, as well as why `print $fh[23] “stuff\n”‘ does’t work. Mixing notations between the OO and IO notations is perilous. If you always use arrow syntax for method calls, and nothing else, you’ll not be surprised.

How do I sort a hash by the hash value?

Here’s a program that prints the contents
of the grades hash, sorted numerically by the hash value:

#!/usr/bin/perl -w

# Help sort a hash by the hash ‘value’, not the ‘key’.
to highest).
sub hashValueAscendingNum {
$grades{$a} <=> $grades{$b};
}

# Help sort a hash by the hash ‘value’, not the ‘key’.
# Values are returned in descending numeric order
# (highest to lowest).
sub hashValueDescendingNum {
$grades{$b} <=> $grades{$a};
}

%grades = (
student1 => 90,
student2 => 75,
student3 => 96,
student4 => 55,
student5 => 76,
);

print “\n\tGRADES IN ASCENDING NUMERIC ORDER:\n”;
foreach $key (sort hashValueAscendingNum (keys(%grades))) {
print “\t\t$grades{$key} \t\t $key\n”;
}

print “\n\tGRADES IN DESCENDING NUMERIC ORDER:\n”;
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print “\t\t$grades{$key} \t\t $key\n”;
}

How to read file into hash array ?

open(IN, “<name_file”)
or die “Couldn’t open file for processing: $!”;
while (<IN>) {
chomp;
$hash_table{$_} = 0;
}
close IN;

print “$_ = $hash_table{$_}\n” foreach keys %hash_table;

How do you find the length of an array?

$@array

What value is returned by a lone return; statement?

The undefined value in scalar context, and the empty list value () in list context.
This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called.

What is the difference between /^Foo/s and /^Foo/?

The second would match Foo other than at the start of the record if $* were set.
The deprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, you suppress any settings of that spooky variable, and force your carets and dollars to match only at the ends of the string and not at ends of line as well — just as they would if $* weren’t set at all.

Does Perl have reference type?

Yes. Perl can make a scalar or hash type reference by using backslash operator.
For example
$str = “here we go”; # a scalar variable
$strref = \$str; # a reference to a scalar

@array = (1..10); # an array
$arrayref = \@array; # a reference to an array
Note that the reference itself is a scalar.

How to dereference a reference?

There are a number of ways to dereference a reference.
Using two dollar signs to dereference a scalar.
$original = $$strref;
Using @ sign to dereference an array.
@list = @$arrayref;
Similar for hashes.

What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?

5
length() is a built-in prototyped as sub length($), and a scalar prototype silently changes aggregates into radically different forms. The scalar sense of a hash is false (0) if it’s empty, otherwise it’s a string representing the fullness of the buckets, like “18/32” or “39/64”. The length of that string is likely to be 5. Likewise, `length(@a)’ would be 2 if there were 37 elements in @a.

If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{“Foo::”.EXPR}?

The second is disallowed under `use strict “refs”‘.
Dereferencing a string with *{“STR”} is disallowed under the refs stricture, although *{STR} would not be. This is similar in spirit to the way ${“STR”} is always the symbol table variable, while ${STR} may be the lexical variable. If it’s not a bareword, you’re playing with the symbol table in a particular dynamic fashion.

How do I do < fill-in-the-blank > for each element in an array?

#!/usr/bin/perl -w
@homeRunHitters = (‘McGwire’, ‘Sosa’, ‘Maris’, ‘Ruth’);
foreach (@homeRunHitters) {
print “$_ hit a lot of home runs in one year\n”;
}

How do I replace every <TAB> character in a file with a comma?

perl -pi.bak -e ‘s/\t/,/g’ myfile.txt

What is the easiest way to download the contents of a URL with Perl?
Answer:
Once you have the libwww-perl library, LWP.pm installed, the code is this:
#!/usr/bin/perl
use LWP::Simple;
$url = get ‘http://www.websitename.com/’;

How to concatenate strings with Perl?
Method #1 – using Perl’s dot operator:
$name = ‘checkbook’;
$filename = “/tmp/” . $name . “.tmp”;

Method #2 – using Perl’s join function
$name = “checkbook”;
$filename = join “”, “/tmp/”, $name, “.tmp”;

Method #3 – usual way of concatenating strings
$filename = “/tmp/${name}.tmp”;

How do I read command-line arguments with Perl?

With Perl, command-line arguments are stored in the array named @ARGV.
$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.
Here’s a simple program:
#!/usr/bin/perl
$numArgs = $#ARGV + 1;
print “thanks, you gave me $numArgs command-line arguments.\n”;
foreach $argnum (0 .. $#ARGV) {
print “$ARGV[$argnum]\n”;
}

When would local $_ in a function ruin your day?

When your caller was in the middle for a while(m//g) loop
The /g state on a global variable is not protected by running local on it. That’ll teach you to stop using locals. Too bad $_ can’t be the target of a my() — yet.

What happens to objects lost in “unreachable” memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ]; }’ ?

Their destructors are called when that interpreter thread shuts down.
When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code.

Assume that $ref refers to a scalar, an array, a hash or to some nested data structure. Explain the following statements:
Answer:
$$ref; # returns a scalar
$$ref[0]; # returns the first element of that array
$ref- > [0]; # returns the first element of that array
@$ref; # returns the contents of that array, or number of elements, in scalar context
$&$ref; # returns the last index in that array
$ref- > [0][5]; # returns the sixth element in the first row
@{$ref- > {key}} # returns the contents of the array that is the value of the key “key”

How do you match one letter in the current locale?

Answer:
/[^\W_\d]/
We don’t have full POSIX regexps, so you can’t get at the isalpha() <ctype.h> macro save indirectly. You ask for one byte which is neither a non-alphanumunder, nor an under, nor a numeric. That leaves just the alphas, which is what you want.

How do I print the entire contents of an array with Perl?
Answer:
To answer this question, we first need a sample array. Let’s assume that you have an array that contains the name of baseball teams, like this:
@teams = (‘cubs’, ‘reds’, ‘yankees’, ‘dodgers’);
If you just want to print the array with the array members separated by blank spaces, you can just print the array like this:
@teams = (‘cubs’, ‘reds’, ‘yankees’, ‘dodgers’);
print “@teams\n”;
But that’s not usually the case. More often, you want each element printed on a separate line. To achieve this, you can use this code:
@teams = (‘cubs’, ‘reds’, ‘yankees’, ‘dodgers’);
foreach (@teams) {
print “$_\n”;
}

How many ways can we express string in Perl?
Many. For example ‘this is a string’ can be expressed in:
“this is a string”
qq/this is a string like double-quoted string/
qq^this is a string like double-quoted string^
q/this is a string/
q&this is a string&
q(this is a string)

How do you give functions private variables that retain their values between calls?

Create a scope surrounding that sub that contains lexicals.
Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus:
{ my $i = 0; sub next_i { $i++ } sub last_i { –$i } }
creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.

What is the Use of Symbolic Reference in PERL?

How to find type of variable?

What is Grep used for in Perl?

grep ( EXPR, LIST) extract any elements from LIST for which EXPR is TRUE.
Return Value

In scalar context – Number of times the expression returned true

In list context – List of elements that matched the expression

Example

Try out following example:

#!/usr/bin/perl

@list = (1,”Test”, 0, “foo”, 20 );

@has_digit = grep ( /\d/, @list );

print “@has_digit\n”;

It produces following result

1 0 20

What is eval in perl?

Evaluates EXPR at execution time as if EXPR were a separate Perl script. This allows you to use a separate, perhaps user-supplied, piece of Perl script within your program. An eval EXPR statement is evaluated separately each time the function is called.

The second form evaluates BLOCK when the rest of the script is parsed (before execution).

How to substitute a particular string in a file containing millions of records?

$_ = s/ string1 / string2 /g

How we can navigate the XML documents?

What is the difference between die and exit in perl?

Die is exmplained below;

exit Evaluates EXPR, exits the Perl interpreter, and returns the value as the exit value.Always runs all END{} blocks defined in the script (and imported packages) before exiting. If EXPR is omitted, then the interpreter exits with a value of 0. Should not be used to exit from a subroutine; either use eval and die or use return.

Following are the usage…

$ans = <STDIN>;
exit 0 if $ans =~ /^[Xx]/

What is hash in perl?

A hash represents a set of key/value pairs. Actaully hash are type of arrays with the exception that hash index could be a number or string. They are prefixed by % sign as follows:

my %fruit_color = (“apple”, “red”, “banana”, “yellow”);

what is meant ‘die’ in a perl program?

Raise an exception or bail out.

Following are the usage…

die “Can’t cd to spool: $!\n” unless chdir ‘/usr/spool/news’;
or
chdir ‘/usr/spool/news’ or die “Can’t cd to spool: $!\n”
or
open( FILEH, “>/tmp/test” ) || die( “Can’t open file test $!\n” );

what’s is the use of ‘require’ and what does this mean?

Load in external functions from a library at runtime

what does this mean ‘$^O’? tell briefly plse..

Contains the name of the operating system that the current Perl binary was compiled for.

what does this mean : ‘$_’ ?

$_ is a default special varible in perl which store the inputs for further pattern searching.

what are regular expressions?

A regular expression, also referred to as regex or regexp, provides a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. A regular expression is written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification.

Difference between for and foreach?

Using for you can initialize variable, condition check and increment the variables like ‘C’ or like some other languages.
foreach is a function having in perl using you can iterates over the list and you cannot initialize or condition check or increment like ‘for’ in a single line.
We can use both for or foreach for any scenario but Perl author suggest that you can use for where you are counting a number of iteration like conventional for loops. foreach for list based operation where you are access the list from array.

Difference between exec and system in perl?

http://www.scmgalaxy.com/forum/perl-script/t-521.html#522

What is use strict. Explain with example.
strict – Perl pragma to restrict unsafe constructs.

Example:
use strict;
use strict “vars”;
use strict “refs”;
use strict “subs”;
use strict;
no strict “vars”;

use strict “subs”;
The use function allows you to use modules located in the standard liberary. When the strict pragma takes subs as an argument, it will catch any barewords found in the program while it is being internally compiled. If a bareword is found, the program will be aborted with an error message.

use strict “vars”
This generates a compile-time error if you access a variable that was neither explicitly declared (using any of my, our, state, or use vars ) nor fully qualified.

use strict “refs”
This generates a runtime error if you use symbolic references.

More –
http://perldoc.perl.org/strict.html
http://szabgab.com/barewords-in-perl.html

What is CPAN?
CPAN is the Comprehensive Perl Archive Network, a large collection of Perl software and documentation. You can begin exploring from either http://www.cpan.org/ or any of the mirrors listed at http://www.cpan.org/SITES.html.

CPAN is also the name of a Perl module, CPAN.pm, which is used to download and install Perl software from the CPAN archive.you may find the documentation for it by using perldoc CPAN via the command line
More: –
http://www.cpan.org/misc/cpan-faq.html#What_is_CPAN

How to install modules using CPAN or PPM (Perl Package Manager)
Install cpanm to make installing other modules easier
> cpan App::cpanminus (Mac OS X, Win32, X Windows/Linux)

Now install any module you can find in http://www.cpan.org/modules/index.html
cpanm Module::Name
such as to insall local::lib
> cpanm local::lib

ActiveState maintains repositories of precompiled CPAN packages that can be installed with either the PPM command-line client, or the PPM GUI application. To install the DBD-mysql database driver all you have to do is run the ppm install command:
> ppm install DBD-mysql

Alternatively you can run ppm without any parameters to invoke the GUI, search for DBD-mysql, select the DBD-mysql package, and perform the installation:
> ppm

How do you open a file for writing?

open(FH, "> $path") or die $!;

Difference between printf and sprintf in perl ? || print vs sprintf || Difference between print vs sprintf

The printf and sprintf is built-in function. One difference is printf prints it’s output and sprintf returns it’;s value.
Prints the value of LIST interpreted via the format specified by FORMAT to the current output filehandle, or to the one specified by FILEHANDLE.

Syntax
printf FILEHANDLE FORMAT, LIST
printf FORMAT, LIST

Return Value
0 on failure
1 on success

Effectively equivalent to print FILEHANDLE sprintf(FORMAT, LIST)

Try out following example:
#!/usr/bin/perl -w
printf “%d\n”, 3.1415126;
printf “The cost is \$%6.2f\n”,499;
printf “Perl’s version is v%vd\n”,%^V;
printf “%04d\n”, 20;

It will produce following results: Try more options yourself.
3
The cost is $499.00
Perl’s version is v
0020

On the other hand, The sprintf function uses FORMAT to return a formatted string based on the values in LIST. Essentially identical to printf, but the formatted string is returned instead of being printed.

Syntax
sprintf FORMAT, LIST

Return Value
SCALAR, a formatted text string.

Example
Try out following example:
#!/usr/bin/perl -w
$text = sprintf(“%0d \n”, 9);
print “Formated string $text\n”;

It will produce following result:
Formated string 9

What arguments do you frequently use for the Perl interpreter and what do they mean?
-w to show warning
-d to debug
-c to compile only not run
-e Which executes

You can check to see if your script has compiled successfully by using the –c switch. This used to check for syntax errors.
perl –c scriptname.pl

To Run on command line:executes the program given as an argument
perl –e ‘print “hello world\n”;’ unix/linux

With Warning Pragma
Perl –w <scriptname>

To start perl debugger on the file name specified as an argument
Perl –d <scriptname>

What do the symbols $ @ and % mean when prefixing a variable?
$  – To Define Scalar Variable
@ – To Define an Array
% – To define a hash

What elements of the Perl language could you use to structure your code to allow for maximum re-use and maximum readability?
It could be Subroutine, Module, Class, Package or objects. Questions should be more clear.

Why do you program in Perl?
Practice Report and Extraction Language
Interpreted Language optimized for scanning arbitrary test files, extracting information from them, and printing based on that information.
Very Powerful String handling features
Available for all platforms

Speed of Development
You can  enter the  program in a text file and just run it. It is an interpretive language; no compiler is neede
It is Powerful
The Regular expression of Perl are extremely powerful
Uses sophisticated pattern matching techniques to scan large amounts of data quickly.

Portability
Perl is a standard language and is available on all platforms.
Free version are available on the internet

Editing Perl programs
No sophisticated editing tool is needed
Any simple text editor like Notepad or vi will do

Flexibility
Perl Does not limit the size of your data
If Memory is available, perl can handle the whole file as a single string.
Allow one to write simple programs to perform complex task

What’s your favorite module and why?
use DBI;
use Getopt::Long;
use Time::Local;
use List::Compare;
use Log::Log4perl;
use CGI;
use HTML::Template;
use Data::Dumper;
use LWP;
use File::Find;

What is a hash?

A hash can be initialized with a list, where elements of the list are key and value pairs:

my %food_color = ( “Apple” => “red”, “Banana” => “yellow”, “Lemon” => “yellow”);

%age = ( “Nat”, 24, “Jules”, 25, “Josh”, 17 );
is equivalent to
$age{“Nat”} = 24; $age{“Jules”} = 25; $age{“Josh”} = 17;

$hash{“other”}

Only use the % when referring to the hash as a whole such as %boss
Hashes is that their elements are stored in an internal order convenient for efficient retrieval. it will come out in an unpredictable disorder.
When Referring to the value associated with a particular key, that’s a single scalar value, so is $ is called for.
When referring to one element of an array, you also use a $.
You can store only scalar value in a hash. References, however, are scalars. This solves the problem of storing multiple values for one key by making $hash{$key} a reference to an array containing values of $key.

What purpose does each of the following serve: -w?
Perl –w <scriptname>
Or
#! /usr/bin/perl –w
Or
use warnings; perl version 5.6 and later

The –w switch prints warnings about ambiguous identifiers, such as variables that have been used only once, improper conversion of stings and numbers etc

What is the difference between ‘use’ and ‘require’ function?
Use:
1. the method is used only for modules (only to include .pm type file)
2. the included object are verified at the time of compilation.
3. No Need to give file extentsion.
Require:
1. The method is used for both libraries ( package ) and modules
2. The include objects are varified at the run time.
3. Need to give file Extension.

Explain the difference between my and local.
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.

In the example below, $::a refers to $a in the ‘global’ namespace.

‘local’ temporarily changes the value of the variable, but only within the scope it exists in.

$a = 3.14159;
{
local $a = 3;
print “In block, \$a = $a\n”;
print “In block, \$::a = $::a\n”;
}

print “Outside block, \$a = $a\n”;
print “Outside block, \$::a = $::a\n”;

# This outputs In block,

# This outputs

In block, $a = 3
In block, $::a = 3
Outside block, $a = 3.14159
Outside block, $::a = 3.14159

‘my’ has no effect on the global $a, even inside the block.

$a = 3.14159;
{
my $a = 3;
print “In block, \$a = $a\n”;
print “In block, \$::a = $::a\n”;
}
print “Outside block, \$a = $a\n”;
print “Outside block, \$::a = $::a\n”;

# This outputs
In block, $a = 3
In block, $::a = 3.14159
Outside block, $a = 3.14159
Outside block, $::a = 3.14159

What is the difference between for & foreach?
What is the difference between exec & system?
What is the difference between map & grep?
What is the difference between sysread & read?
What is the difference between chop & chomp?
What is the difference between qq,qw & qx?
What is the difference between rand & srand?
What is the difference between exists and defined?
What is the difference between use and require?
What is the difference between eval & study?

Tagged : / / / / / / / / / / / / / / /

How to Select the Right Software version Control Product?

software-version-control-product

Original link: http://www.cmcrossroads.com/cm-articles/275-articles/14286-selecting-the-right-software-version-control-product

Selecting the Right Software Version Control Product Written by Mike Feighner For many years, I worked loyally for the same company where my expertise was restricted to one single software version control tool—the one that was already in place. I was not involved with determining whether the selected tool was appropriate for the company’s needs; my role was to learn it well and use it within the accepted standards, guidelines, and internally approved processes. When I recently found myself back in the job market, I realized that there were many other version control tools in use in the industry. I then began to consult with other engineers in the field and gathered data from them on which version control tools their organizations were using and the selection criteria they used in choosing a version control tool for their organization. This experience opened up a whole new world for me and soon I realized that selecting and implementing the right tools was essential for the success of any software or systems development effort. From this experience, I have drawn up a checklist of version-control-tool criteria to aid an organization in selecting the best tool. Although there are many good descriptions available on the Internet about the many tools currently on the market, I do not recommend one specific tool over the other, because some tools may fit great in one organization, but fail in another. My goal here is to suggest a partial framework for deciding which tool best fits your needs while at the same time adhering to configuration management best practices. First, you will need to define your organization’s goals, which could include any or all of the following: Good documentation should accompany your tool purchase. The tool should be portable to more than one platform. If your organization is spread out over different time zones or even across international borders, your tool should support a multi-site rather than a single-site function. The cost should be affordable. The tool should be easy to use. The tool should easily support branching and merging. The tool should have the ability to lock a file when being edited to prevent two engineers from editing the same file simultaneously. The tool should be able to accurately merge changes between two or more files. The tool should log a history of changes with notes on who made the change and why the change was made. The tool should have the ability to establish immutable baselines. Next, you will need to review your organization’s requirements for software version control and carefully review the various software tools on the market to determine which one best matches your organization’s needs. Some may be better suited for your project than others. Selecting the wrong tool can have devastating effects on your team’s effort. Lack of a good version control tool can be a major cause for delays and problems during your organization’s application development. The project will run over cost and behind schedule and can be prone to risks associated with the manual management and distribution of your project’s dependencies. Unauthorized changes and results will occur, and the customer will not be satisfied. The tool you select should not impede the implementation of configuration management best practices, which serve as a means to add value to the process, improve quality, and increase productivity. The following are some, but not all, of the questions you will need to consider. Documentation Is the tool well documented? Is support documentation available on this tool’s installation and for the tool’s use by both administrators and developers? As a reference manual, the tool’s documentation should adequately describe the tool’s features—each dialog box, tab, field, button, etc. It should answer a user’s questions about completing a specific task in a clear and concise way. Frequently, the user documentation is available in the tool’s help pull-down menu or can be downloaded electronically from the vendor’s website. Portability Is the tool portable? Can it be used on multiple platforms and operating systems? From a business perspective, your software team will be supporting a broad user market occupying various platforms, including Windows, Mac OS, or some flavor of UNIX. Your tool should be compatible on any of these platforms, as each release will simultaneously need a separate version to support each platform of your user base. Multi-site vs. Single Site Is your team located at one location site, or is your team globally distributed across the nation and across different time zones throughout the world? A “single site” constitutes one physical location such as a single building or office. A “multisite” constitutes an organization in more than one office or location in a single time zone, in multiple time zones within one country or in multiple countries. If your organization is spread out over various time zones or even across international borders, your tool should support a multi-site rather than a single-site function. A multi-site project established as a set of several individual independent single-site systems would be prone to added costs and risks associated with the manual management and distribution of the project’s dependencies. Life for a multisite organization would be a lot easier to maintain a single multisite system with access to one shared repository. A single-site organization would be wise to select a single-site system over the additional costs of a multi-site system Cost What are the costs and terms of licensing of the tool? Is it something your organization can afford? Generally, a tool designed for a large organization will have a much larger cost than one designed for a smaller organization. No one should assume paying a higher cost for your tool will solve all of your problems. Even a high cost tool may fall sort of satisfying your organization’s needs. Your decision should consider overall cost and your organization’s needs. Supporting your organization’s needs should never be underfunded. Ease of Use How easy is it to install and deploy the system? Will the tool be dependent on other tools to conduct software builds, or are some of these capabilities already an integral part of the tool? Is this a tool that is easy to use from the first day of installation throughout the entire development lifecycle? Will training and customer support be available? Will the tool require training an in-house administrator dedicated to the administration of the tool? If you are not able to immediately pick up a source code management system and start building your site, odds are it is not entirely user friendly. Ultimately, the key to a successful deployment of a source code management system is reliability and ease-of-use. A tool that is difficult to use will likely conceal the functional benefits that it would otherwise provide. If training is an affordable option for your organization, consider whether it is available through the vendor or through an unbiased third party. For a lower-cost approach in the long term, consider sending a representative from your organization to a vendor training event who will later write up a training program for your own company-based organization. Branching Does the tool accommodate branch creation? The capability to create a branch should allow duplication of an object under revision control. Thus, code modifications can happen securely in parallel along both branches at the same time whether the change involves adding a new requirement or attempting to resolve an issue from an earlier release. The tool you select should support your particular choice of branching strategy, be it by revision or release via a simple copybranch or by creating adelta branch off of the main branch or trunk. Or the tool may go a step further by creating streams that include supporting metadata and workflow automation as an enhancement in managing multiple variants in the code. Branching is one of the most important features to consider in your choice of a good source control management system as it allows you to easily support at the same time the same source code and a parallel subset of the same code being modified securely to support either a new requirement or a bugfix from an earlier release. Merging Does the tool allow merges of changes and assists in resolving conflicts between different edits to the same file? Can a merge be done via a graphical user interface or on a command line? Take into consideration that merging concurrent changes made by different developers can increase the amount of effort to resolve conflicts and achieve a merge safely. The best advice in such cases is to merge little and merge often. File Locking Does the system have a means of preventing concurrent access to the same file? Does it prevent more than one user at a time from writing to the file until the current user either checks in the file or cancels the checkout? History of Changes Does the tool maintain a log of the history of changes? Can the tool display the history of changes graphically, as in a version tree? Does the tool easily identify the current baselined version and list previous baselined versions? A history change log that maintains accurate records facilitates traceability through the code’s lifecycle, from its beginning to its eventual release and beyond. A change history log can trace a change back its origins to who made the change and to the authority who authorized the change. It plays a vital role in baselining the code. This is a basic requirement of any organization wishing to maintain proper controls and compliance. Baselining Baselining, also known as setting a control point for your code, lets you know the exact versions of all source code and other configuration items that were included in a release. Does the tool have a way of baselining the code (be it via labeling, tagging, or snapshots) to a particular version that would allow us to back out and return to the previous baselined version in the event of a problem? Is the baseline immutable? If the tool allows changes to the previously released baseline, it jeopardizes the integrity of the software. A baseline must be locked down to prevent modifications. Any subsequent release should be based on a previously release baseline. Conclusion No one software version control tool can possibly fit every organization’s needs. There is no one size fits all. The right tool should help you safeguard your code and help your process improve productivity and quality. Remember that thorough evaluation and selection of the right tool will require funding, but this vetting must stay within your organization’s budget. Careful selection of the appropriate version control tool will help your firm improve productivity and quality and ensure that you are adhering to industry standards regarding configuration management best practices. About the Author Mike Feighner has more than twenty years’ experience in information technology in the aerospace industry, including more than ten years in configuration management. Mike graduated from San Jose State University with a bachelor’s degree in German and has a master’s degree in political science from the University of Tübingen in Germany and a master’s degree in software engineering from National University.

Tagged : / / / / / / / / / / / / / / /

Use of p4 duplicate command | P4 Command Guide

p4-duplicate-command

Use of p4 duplicate command

Problem Area is –
Is there any possibility to rename branch name? as directory rename is possible?

Solution is – p4 duplicate command

What the command ‘p4 duplicate’ was implement to do was create a duplicated revision of a folder as if it always existed. This is explained in the ‘p4 help duplicate’, I have copied below:

Duplicate revisions as if they always existed.  All aspects of
   the source revisions are mirrored into the target revisions,
   including changelist number, date, attributes, and contents.
   The target revision must not already exist, and the target file
must not be opened (for any operation) on any client.

Integration records are duplicated as well.

To rename branch names is possible with the process of a deep rename operation.

p4 duplicate //depot/Jam/MAINds/… //depot/Jam/MAIN/…

The above command will create an exact copy of the branch you’re duplicating including its integration history.

Then the duplication source is not wanted anymore, so you will need to use the obliterate command:

p4 obliterate -y //depot/Jam/MAINds/…

You can find more information about “p4 duplicate” by running the “p4 help duplicate” command.

If you have any further questions please let me know.

Reference –

Perforce Support and

http://maillist.perforce.com/pipermail/perforce-user/2010-November/027364.html

Tagged : / / / / / / / / / / / / / /