How to read and write a single character?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • perlrmhu
    New Member
    • Dec 2011
    • 10

    How to read and write a single character?

    I need to read a file on Unix server that has only one line with a character on it. My script needs to read in the character. If the character is 1, the script stops and exit. Otherwise, the script runs. Befoere the scripts ends, write the "0" to replace "1". I wrote some code like below. but it does not work and get error of "Reference to nonexistent group in regex; marked by <-- HERE in m/^\1 <-- HERE /". Can someone help? Thanks.
    Code:
    #!/usr//bin/perl -w
    use Net::SFTP::Foreign;
    open(F, 'testRead_line.txt');
    while () {
    print "line = $_ \n";
    if ($_ =~ m/^\1/) {
    print "The script has already been running. Exit. \n";
    exit (0);
    }
    else {
    print "start running the script. \n";
    }
    }
  • chorny
    Recognized Expert New Member
    • Jan 2008
    • 80

    #2
    \1 has special meaning in regexes.

    Code:
    #!/usr//bin/perl -w
    use Net::SFTP::Foreign;
    open(my $fh, '<','testRead_line.txt') or die;
    while (my $line=<$fh>) {
    chomp($line);
    print "line = $line\n";
    if ($line eq '1') {
    print "The script has already been running. Exit. \n";
    exit (0);
    }
    else {
    print "start running the script. \n";
    }
    }

    Comment

    • perlrmhu
      New Member
      • Dec 2011
      • 10

      #3
      Thank you Chorny. The code you suggested works great! Can you please let me know how to write the single character "0" replacing "1" on the line in the file? Thanks,

      Comment

      • chorny
        Recognized Expert New Member
        • Jan 2008
        • 80

        #4
        If your file has no other information, close file handle, open it for writing and write "0\n".

        Comment

        Working...