The Perl language in general

perl script, how to perl, tutorial perl




FAQ 4.68 Why does passing a subroutine an undefined element in a hash create it?

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

——————————————————————–

4.68: Why does passing a subroutine an undefined element in a hash create it?

    (contributed by brian d foy)

    Are you using a really old version of Perl?

    Normally, accessing a hash key’s value for a nonexistent key will *not*
    create the key.

            my %hash  = ();
            my $value = $hash{ ‘foo’ };
            print "This won’t print\n" if exists $hash{ ‘foo’ };

    Passing $hash{ ‘foo’ } to a subroutine used to be a special case,
    though. Since you could assign directly to $_[0], Perl had to be ready
    to make that assignment so it created the hash key ahead of time:

        my_sub( $hash{ ‘foo’ } );
            print "This will print before 5.004\n" if exists $hash{ ‘foo’ };

            sub my_sub {
                    # $_[0] = ‘bar’; # create hash key in case you do this
                    1;
                    }

    Since Perl 5.004, however, this situation is a special case and Perl
    creates the hash key only when you make the assignment:

        my_sub( $hash{ ‘foo’ } );
            print "This will print, even after 5.004\n" if exists $hash{ ‘foo’ };

            sub my_sub {
                    $_[0] = ‘bar’;
                    }

    However, if you want the old behavior (and think carefully about that
    because it’s a weird side effect), you can pass a hash slice instead.
    Perl 5.004 didn’t make this a special case:

            my_sub( @hash{ qw/foo/ } );

——————————————————————–

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don’t have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you’d like to help maintain the perlfaq, see the details in
perlfaq.pod.

No Comments

Using end of line in character class

Hi,

I am trying extract specific value out of URL query. Here is the
example.

my $text = "http://localhost/news.xmlapi/
StoryResponse.aspxServ=RT&Pkey=1245445784nSP376208-20090619210944-2-
FRT";
#my $text = "http://localhost/news.xmlapi/StoryResponse.aspx?
Pkey=124544 84nSP376208-20090619210944-2-FRT&Serv=RT";

if($text =~ m/&*Serv=(.*)[&$]/)
{
        printf "$1\n";
} else {

        printf "not matched";

}

it gives follwing error.
Unmatched [ in regex; marked by <– HERE in m/&*Serv=(.*)[ <– HERE
&5.008008/ at ./x.pl line 6

If I remove $ from character class then it works fine for first text.
But it does not work for commented definition of text which is also
possible case.

I don’t know what is wrong with $(end of line) in character classs.

Thanks,
Nilesh

Comments (2)

FAQ 5.6 How do I make a temporary file name?

This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

——————————————————————–

5.6: How do I make a temporary file name?

    If you don’t need to know the name of the file, you can use "open()"
    with "undef" in place of the file name. In Perl 5.8 or later, the
    "open()" function creates an anonymous temporary file:

            open my $tmp, ‘+>’, undef or die $!;

    Otherwise, you can use the File::Temp module.

            use File::Temp qw/ tempfile tempdir /;

            $dir = tempdir( CLEANUP => 1 );
            ($fh, $filename) = tempfile( DIR => $dir );

            # or if you don’t need to know the filename

            $fh = tempfile( DIR => $dir );

    The File::Temp has been a standard module since Perl 5.6.1. If you don’t
    have a modern enough Perl installed, use the "new_tmpfile" class method
    from the IO::File module to get a filehandle opened for reading and
    writing. Use it if you don’t need to know the file’s name:

            use IO::File;
            $fh = IO::File->new_tmpfile()
            or die "Unable to make new temporary file: $!";

    If you’re committed to creating a temporary file by hand, use the
    process ID and/or the current time-value. If you need to have many
    temporary files in one process, use a counter:

            BEGIN {
            use Fcntl;
            my $temp_dir = -d ‘/tmp’ ? ‘/tmp’ : $ENV{TMPDIR} || $ENV{TEMP};
            my $base_name = sprintf "%s/%d-%d-0000", $temp_dir, $$, time;

            sub temp_file {
                    local *FH;
                    my $count = 0;
                    until( defined(fileno(FH)) || $count++ > 100 ) {
                            $base_name =~ s/-(\d+)$/"-" . (1 + $1)/e;
                            # O_EXCL is required for security reasons.
                            sysopen FH, $base_name, O_WRONLY|O_EXCL|O_CREAT;
                            }

                    if( defined fileno(FH) ) {
                            return (*FH, $base_name);
                            }
                    else {
                            return ();
                            }
                    }

            }

——————————————————————–

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don’t have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you’d like to help maintain the perlfaq, see the details in
perlfaq.pod.

No Comments

Calling 'C' routines from perl.

Hi All:

  Can someone let me know how to invoke a ‘C’ routine from perl. I
have to develop an application
  that requires Perl and C interactions. I need to know this in
detail. Please provide me with exmples or referances where I can learn
this.

   Thanks for the help in advance.

Regards,
Prathap

Comments (8)

Importent info

must read if you have a site then you contect me in this adderess
provide me your site URL and your wish
yaqubkha…@gmail.com
you have or not but you visit first these site
yaqubairlines.blogspot.com
yaqubluxuryliving.blogspot.com
yaqubsoftwear.blogspot.com
yaqubhealth.blogspot.com
yaqubmedical.blogspot.com
only one time all over the month click in your favirte add and check
it

No Comments

FAQ 4.31 How can I split a [character] delimited string except when inside [character]?

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

——————————————————————–

4.31: How can I split a [character] delimited string except when inside [character]?

    Several modules can handle this sort of parsing–"Text::Balanced",
    "Text::CSV", "Text::CSV_XS", and "Text::ParseWords", among others.

    Take the example case of trying to split a string that is
    comma-separated into its different fields. You can’t use "split(/,/)"
    because you shouldn’t split if the comma is inside quotes. For example,
    take a data line like this:

            SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"

    Due to the restriction of the quotes, this is a fairly complex problem.
    Thankfully, we have Jeffrey Friedl, author of *Mastering Regular
    Expressions*, to handle these for us. He suggests (assuming your string
    is contained in $text):

             @new = ();
             push(@new, $+) while $text =~ m{
                     "([^\"\\]*(?:\\.[^\"\\]*)*)",?  # groups the phrase inside the quotes
                    | ([^,]+),?
                    | ,
                    }gx;
             push(@new, undef) if substr($text,-1,1) eq ‘,’;

    If you want to represent quotation marks inside a
    quotation-mark-delimited field, escape them with backslashes (eg, "like
    \"this\"".

    Alternatively, the "Text::ParseWords" module (part of the standard Perl
    distribution) lets you say:

            use Text::ParseWords;
            @new = quotewords(",", 0, $text);

——————————————————————–

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don’t have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you’d like to help maintain the perlfaq, see the details in
perlfaq.pod.

No Comments

FAQ 4.28 How do I change the Nth occurrence of something?

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

——————————————————————–

4.28: How do I change the Nth occurrence of something?

    You have to keep track of N yourself. For example, let’s say you want to
    change the fifth occurrence of "whoever" or "whomever" into "whosoever"
    or "whomsoever", case insensitively. These all assume that $_ contains
    the string to be altered.

            $count = 0;
            s{((whom?)ever)}{
            ++$count == 5       # is it the 5th?
                ? "${2}soever"  # yes, swap
                : $1            # renege and leave it there
                    }ige;

    In the more general case, you can use the "/g" modifier in a "while"
    loop, keeping count of matches.

            $WANT = 3;
            $count = 0;
            $_ = "One fish two fish red fish blue fish";
            while (/(\w+)\s+fish\b/gi) {
                    if (++$count == $WANT) {
                            print "The third fish is a $1 one.\n";
                            }
                    }

    That prints out: "The third fish is a red one." You can also use a
    repetition count and repeated pattern like this:

            /(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;

——————————————————————–

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don’t have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you’d like to help maintain the perlfaq, see the details in
perlfaq.pod.

Comments (6)

FAQ 4.63 Why don't my tied hashes make the defined/exists distinction?

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

——————————————————————–

4.63: Why don’t my tied hashes make the defined/exists distinction?

    This depends on the tied hash’s implementation of EXISTS(). For example,
    there isn’t the concept of undef with hashes that are tied to DBM*
    files. It also means that exists() and defined() do the same thing with
    a DBM* file, and what they end up doing is not what they do with
    ordinary hashes.

——————————————————————–

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don’t have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you’d like to help maintain the perlfaq, see the details in
perlfaq.pod.

No Comments

Reading perl substitute expressions from a file

A simple substitution in perl is done by
  $variable =~ s/string1/string2/i;
  $variable =~ s/string3/string4/g;
  print $variable;

This works fine but I would have to tailor the program for each specific
case.

I would like to put these is a file D:/TEMP/perlString.txt and then write a
perl program to read and execute them.

I have tried something like this but have been unsuccessful.
Is it even possible?

Basic logic I tried:

my $inFile= "D:/TEMP/perlString.txt";
open(INFILEH, $inFile);
while (<INFILEH>)
{
    chomp;
    $perlExpr = $_;
    $variable =~ $perlExpr;
}

print $variable;

Comments (5)

FAQ 4.7 How do I multiply matrices?

This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

——————————————————————–

4.7: How do I multiply matrices?

    Use the Math::Matrix or Math::MatrixReal modules (available from CPAN)
    or the PDL extension (also available from CPAN).

——————————————————————–

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don’t have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you’d like to help maintain the perlfaq, see the details in
perlfaq.pod.

Comments (2)